问题
I am reading an xml file using dataset and then i am creating a datagridview and assigning the table from dataset to datagridview.datasource dynamically. The problem i am facing here is, i want to add a combobox for one cell in datagridview.
Below is my code :
datagridview1.AllowUserToAddRows = false;
datagridview1.AllowUserToDeleteRows = false;
datagridview1.RowHeadersVisible = false;
datagridview1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
datagridview1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
datagridview1.DataMember = "";
datagridview1.DataSource = my_dataTable;
datagridview1.Columns["first name"].ReadOnly = true;
datagridview1.Columns["Second name"].Visible = false;
datagridview1.Columns["place"].Visible = false;
datagridview1.Columns["address"].Visible = false;
string[] datasource = { "add1", "add2" };
DataGridViewComboBoxCell combo = new DataGridViewComboBoxCell();
combo.DataSource = datasource;
datagridview1.Rows[2].Cells[2] = combo;
It is giving me datagridviewcomboboxcell value is not valid error.If i give some value then it runs well but not able to see the combobox in datagridview.
回答1:
You can use the DataSource
to feed to Items
, but using a simple string array will not work.
Instead you can convert the array to a List<string>
:
string[] datasource = { "add1", "add2" };
DataGridViewComboBoxCell combo = new DataGridViewComboBoxCell();
combo.DataSource = datasource.ToList();
DGV.Rows[2].Cells[2] = combo;
To set a value you can use..
combo.Value = combo.Items[0];
..after having set the cell.
For better control, especially for having spearate Display
- and ValueMembers
you can switch to a Dictionary
or use a List<someClass>
..
来源:https://stackoverflow.com/questions/30666665/how-to-add-a-combo-box-in-a-datagrid-view-for-only-one-cell-dynamically