Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define DataGridView Column type Programmatically

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?

like image 525
funerr Avatar asked Oct 15 '11 22:10

funerr


People also ask

How to change column type in DataGridView at runtime?

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.

How to change DataGridView column type in Vb net?

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.

Which of the following is the standard column type in the datagrid?

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.


1 Answers

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.

like image 103
ChrisF Avatar answered Oct 01 '22 04:10

ChrisF