General rule of thumb for Adding Tables and Columns to the Windows Forms DataGrid control:
Note: when programmatically specifying column styles, always create DataGridColumnStyle objects and add them to the GridColumnStylesCollection object before adding DataGridTableStyle object to the GridTableStylesCollection object.
1. In order to display data in the table, you must first bind the DataGrid control to a DataSet.
2. Declare new table style and set its mapping name.
3. Declare a new column style and set its mapping name and other properties.
4. Call the Add method of GridCoulmnStylesCollection object to add the column to the table style.
5. Call the Add method of the GridTableStylesCollection object to add the table style to the data grid.
Follow this simple sample:-
Imports System.Data.OleDb
Dim strConn As String
Dim strSQL As String
Dim Conn As OleDbConnection
Dim objDA As OleDbDataAdapter
Dim objDS As New DataSet()
'Pass the Connection string to OleDbConnection object.
Conn = New OleDbConnection(strConn)
'Build the SQL strings.
strSQL = "SELECT SubTypeID, SubTypeName " & _
"FROM SubType ORDER BY SubTypeName"
'Initialize the OleDbDataAdapter with SQL and Connection string,
'and then use the OleDbAdapter to fill the DataSet with data.
objDA = New OleDbDataAdapter(strSQL, Conn)
objDA.Fill(objDS, "SubType")
'Bind the DataSet to DataGrid.
DataGrid1.SetDataBinding(objDS, "SubType")
'Create DataGridTableStyle and map it to the data table.
Dim subtypeTableStyle As New DataGridTableStyle()
subtypeTableStyle.MappingName = "SubType"
'Create ColumnStyle and set its mapping name & other properties.
Dim colSubTypeID As New DataGridTextBoxColumn()
colSubTypeID.HeaderText = "SubTypeID"
colSubTypeID.MappingName = "SubTypeID"
colSubTypeID.Width = 0
Dim colSubTypeName As New DataGridTextBoxColumn()
colSubTypeName.HeaderText = "Sub Type"
colSubTypeName.MappingName = "SubTypeName"
colSubTypeName.Width = 100
'Call the Add method of GridColumnStylesCollection object to add the column to the table style.
subtypeTableStyle.GridColumnStyles.Add(colSubTypeID)
subtypeTableStyle.GridColumnStyles.Add(colSubTypeName)
'Call the Add method of GridTbaleStylesCollection object to add the table style to the data grid.
grdSubType.TableStyles.Add(subtypeTableStyle)
grdSubType.TableStyles("SubType").ReadOnly = True
grdSubType.TableStyles("SubType").AllowSorting = False
Catch Excep As System.Exception
MessageBox.Show(Excep.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.