Sample Application
The sample application binds the DataGrid to the SQL Server Northwind sample database Customers table, and it sets the width of the CompanyName column to 200 pixels. It also has a button that hides or shows the CustomerID column.
Follow these steps to create a new Visual Basic Windows Application project:
Start Microsoft Visual Studio .NET.
On the File menu, point to New, and then click Project.
In the New Project dialog box, click Visual Basic Project under Project Types, and then click Windows Application under Templates. By default, Form1 is added.
Drag a DataGrid control (DataGrid1) and a Button control (Button1) from the toolbox to the form.
Double-click the form background to see the event code. Add the following code to the top of the code window:Imports System.Data.SqlClient
Add the following member variable to the form declaration:Dim ts As DataGridTableStyle
Add the following code to the Form.Load event:’
’ Fill DataSet
’
Dim con As New SqlConnection(“server=localhost;integrated security=true;database=northwind”)
Dim daCust As New SqlDataAdapter(“Select * From Customers”, con)
Dim ds As New DataSet()
daCust.Fill(ds, “Cust”)
’
’ Bind to grid
’
DataGrid1.DataSource = ds.Tables!Cust
’
’ Get CurrencyManager
’
Dim cm As CurrencyManager
cm = CType(Me.BindingContext(ds.Tables!Cust), CurrencyManager)
’
’ Create the DataGridTableStyle object and modify it
’
ts = New DataGridTableStyle(cm)
ts.MappingName = “Cust”
ts.GridColumnStyles(1).Width = 200
DataGrid1.TableStyles.Add(ts)
NOTE: You may have to modify the connection string based on your environment.
Switch back to the form designer, double-click Button1, and then add the following code to the Button1.Click event. The event code hides and unhides the column by changing the width between 0 and 75 pixels (75 is the default).ts.GridColumnStyles(0).Width = 75 - ts.GridColumnStyles(0).Width
Run the application. The CompanyName column is now between two and three times as wide as the other columns. Click Button1 several times. The CustomerID column disappears and reappears.
back to the top
Troubleshooting
Make sure that the DataGridTableStyle.MappingName matches the name of the DataTable that you bind to. Otherwise, the DataGrid uses the default DataGridTableStyle.
Make sure that you add the DataGridTableStyle object to the TableStyles collection of the DataGrid. Otherwise, the DataGrid uses the default DataGridTableStyle.
Make sure that the CurrencyManager that you get is the same to which the DataGrid is bound. Otherwise, the DataGrid uses the default DataGridTableStyle. The following is another method that is more generic than hard-coding the DataTable: cm = CType(Me.BindingContext(DataGrid1.DataSource, DataGrid1.DataMember), CurrencyManager)
Make sure that you modify the connection string, the SELECT statement, and the table names to match your database. Click here for more info