|
Manually adding DataGridView columns
Published: 5/17/2008 |
|
There are times when you may want to add columns to a DataGridView that are not directly bound to any data, or build an entire DataGridView that is unbound. You may even want to do this at runtime dynamically, creating different types of columns depending on the type of data you are working with. If you've only ever used the control designed to configure a DataGridView, this process might seem a little less than straightforward, but it's tied to the types of columns that are addded to the control when it is first configured. Consider the example where you may want a DataGridView with two columns - one allow regular text input, the other displaying a checkbox to the user. The following code will achieve that effect:
VB:Dim clsCol1 As DataGridViewTextBoxColumn = New DataGridViewTextBoxColumn() clsCol1.HeaderText = "Column 1" clsCol1.ValueType = GetType(System.String) Me.dataGridView1.Columns.Add(clsCol1) Dim clsCol2 As DataGridViewCheckBoxColumn = New DataGridViewCheckBoxColumn() clsCol2.HeaderText = "Column 2" clsCol2.ValueType = GetType(System.Boolean) Me.dataGridView1.Columns.Add(clsCol2)
DataGridViewTextBoxColumn clsCol1 = new DataGridViewTextBoxColumn(); clsCol1.HeaderText = "Column 1"; clsCol1.ValueType = typeof(System.String); this.dataGridView1.Columns.Add(clsCol1); DataGridViewCheckBoxColumn clsCol2 = new DataGridViewCheckBoxColumn(); clsCol2.HeaderText = "Column 2"; clsCol2.ValueType = typeof(System.Boolean); this.dataGridView1.Columns.Add(clsCol2);
.NET offers the following column types:
In addition you can create a class that inherits from DataGridViewColumn, effectively creating your own custom column type, allowing the DataGridView to be extended in virtually any way possible.
Questions or Comments? .
VB to C# and C# to VB translation provided by Instant C# and Instant VB.