SUMMARY
When you bind a Windows Form
DataGrid control, the
DataGrid builds a
DataGridTableStyle object that contains default properties of the grid column
objects. However, you cannot access or modify a
DataGridTableStyle object that is built this way. You can build one in code, or you
can use the Property pane at design-time to add a
DataGridTableStyle object to the
DataGrid.TableStyles collection.
This step-by-step article describes how to
programmatically use the
DataGrid control to build a
DataGridTableStyle object that you can modify on the fly.
To do this,
pass the
CurrencyManager object that the
DataGrid control is bound to, to the
DataGridTableStyle constructor:
Dim ts As New DataGridTableStyle(cm)
back to the
top 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
back to the top