I need a way in which I can define the column type at run-time.
Here is my code:
foreach (DataGridViewColumn column in this.dataGrid.Columns)
{
???
//i.e. column.type = checkbox
}
How can I define the column type in this foreach loop?
You can't change the type of a DataGridView column after it is created but there is nothing to stop you creating columns as needed at run-time. So, depending on the logic that determines the type of each column, you create columns as needed and add them to the DataGridView.
To change the type of a column using the designer ) on the upper-right corner of the DataGridView control, and then select Edit Columns. Select a column from the Selected Columns list. In the Column Properties grid, set the ColumnType property to the new column type.
DataGridViewTextBoxColumn. The DataGridViewTextBoxColumn is a general-purpose column type for use with text-based values such as numbers and strings. In editing mode, a TextBox control is displayed in the active cell, enabling users to modify the cell value.
I'm not 100% certain I understand you question, but you can specify the column type when you create the column:
foreach (var definition in columnDefinitions) // Some list of what the column types are
{
var columnSpec = new DataColumn
{
DataType = definition.Type, // This is of type System.Type
ColumnName = defintion.Name // This is of type string
};
this.dataGrid.Columns.Add(columnSpec);
}
If you need to change the type once it's been created - you can't do that. The best you can do is delete the columns and recreate them with the new types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With