简体   繁体   中英

Adding a Combobox in DataGridView through Datatable

I have a DataGridView and I am populating it through a DataTable . On initializing, I add DataColumns to the DataTable and then set the DataSource of the DataGridView to the DataTable. Here is the code:

DataTable mTable    = new DataTable("Test");

DataColumn  col = new DataColumn;
col.DataType      = System.Type.GetType("System.Boolean");
col.ColumnName  = "First";
col.ReadOnly    = false;
mTable.Columns.Add(col);

col            = new DataColumn;
col.DataType    = System.Type.GetType("System.String");
col.ColumnName  = "Second";
col.ReadOnly    = false;
mTable.Columns.Add(col);

this.myGridView.DataSource = mTable;

This works fine however, I want to make one of the columns showup as a combobox. I think I have to do something with the Column's datatype but I am not sure how to do this. Can anyone give me any pointer towards this?

This is old, but I thought I'd try to answer it anyways since I had the same question myself a while ago.

First of all, you cannot make a DataTable column of type DataGridViewComboBoxColumn. DataColumn inherits from System.Data, while DataGridView*Columns inherit from System.Windows.Forms.

What you can try is this: Once your DataTable is bound to your DataGridView, the columns from the DataTable should show up on the DataGridView in the designer. If you then expand the Columns property of your DataGridView, you should see your columns from your DataTable have been added to the list. Select the column that you want, and in the right-hand pane there will be a property called 'ColumnType'. The default type is DataGridViewTextBoxColumn, but you can change it to DataGridViewComboBoxColumn.

将声明更改为: DataGridViewComboBoxColumn column1 = new DataGridViewComboBoxColumn()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM