Define DataGridView Column type Programmatically

后端 未结 6 1807
眼角桃花
眼角桃花 2020-12-10 08:06

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)
{
???
/         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 08:46

    I assume you mean when you create the DataGridView. In that case you can define it in a DataTable and hook it up to the dgv's Datasource:

    For example:

    var columns = new List>();
    columns.Add(new Tuple("Name", "System.String"));
    columns.Add(new Tuple("Selected", "System.Boolean"));
    columns.Add(new Tuple("Id", "System.Int32"));
    var table = new DataTable();
    columns.ForEach(c => table.Columns.Add(new DataColumn(c.Item1) { DataType = Type.GetType(c.Item2) }));
    var dgv = new DataGridView();
    dgv.DataSource = table;
    

提交回复
热议问题