|
|
|
Format DataGrid Columns - WinForms / VB.Net
10
The easiest way to give columns in a DataGrid the look you want is to use a DataGridTableStyle and to add a GridColumnStyle for each column in the grid.
Imports System.Data.OleDb
Dim strSQL As String = "SELECT * FROM Customers"
Dim Connection As New OleDbConnection(strConnection)
Dim DA As New OleDbDataAdapter(strSQL, Connection)
Dim DS As New DataSet
'
' Retrieve "Customers" data, and populate the DataSet
'
DA.Fill(DS, "Customers")
'
' Create a GridTableStyle. Map it to the "Customers" Table.
'
Dim gtStyle As New DataGridTableStyle
gtStyle.MappingName = "Customers"
'
' Create GridColumnStyle objects for the grid columns
'
Dim colStyle1 As New DataGridTextBoxColumn
Dim colStyle2 As New DataGridTextBoxColumn
Dim colStyle3 As New DataGridTextBoxColumn
Dim colStyle4 As New DataGridTextBoxColumn
'
' Hide column 1 by setting its width to 0.
'
With colStyle1
.MappingName = "Customer_ID"
.Width = 0
End With
'
' Set column 2's caption, width and disable editing.
'
With colStyle2
.MappingName = "Customer_Name"
.HeaderText = "Customer"
.Width = 65
.Alignment = HorizontalAlignment.Left
.TextBox.Enabled = False
End With
'
' Set column 3 and 4's caption, width and enable editing.
' Since these values are optional set their Null values.
'
With colStyle3
.MappingName = "Last_Order_Date"
.HeaderText = "Order Date"
.Width = 50
.Alignment = HorizontalAlignment.Center
.NullText = ""
.TextBox.Enabled = True
.Format = "yyyy-MM-dd"
End With
With colStyle4
.MappingName = "Last_Order_Amount"
.HeaderText = "Amount"
.Width = 50
.Alignment = HorizontalAlignment.Right
.NullText = "0"
.TextBox.Enabled = True
.Format = "#0.00"
End With
'
' Add the GridColumnStyles to the DataGrid's Column Styles collection.
' Place the "ID" column (col 1) last since it is not visible.
'
With gtStyle.GridColumnStyles
.Add(colStyle1)
.Add(colStyle2)
.Add(colStyle3)
.Add(colStyle4)
End With
'
' Add the GridTableStyle to the DataGrid
'
DataGrid.TableStyles.Add(gtStyle)
'
' Bind the DataGrid to the DataSet. Expand and navigate to the first row.
'
If DS.Tables(0).Rows.Count > 0 Then
With DataGrid
.DataSource = DS.Tables(0)
.Expand(-1)
.NavigateTo(0, "Customers")
End With
End If




Babak Zawari
بابک زواري
============================================================
DAVEZ DESIGNZ - Custom Web and Software Development