如何仅在一个数据单元中动态地在数据网格视图中添加一个组合框 [英] how to add a combo box in a datagrid view for only one cell dynamically
问题描述
我正在使用数据集读取xml文件,然后创建一个datagridview并将表从数据集动态分配给datagridview.datasource。
我在这里面临的问题是,我想为datagridview中的一个单元格添加一个组合框。
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.
下面是我的代码:
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;
这给了我datagridviewcomboboxcell值无效错误。如果我给出一些值,那么它运行良好,但无法在datagridview中看到组合框。
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.
推荐答案
您可以使用 DataSource
输入项
,但是使用简单的字符串数组将不起作用。
You can use the DataSource
to feed to Items
, but using a simple string array will not work.
相反,您可以将数组到 List< string>
:
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];
.. 设置单元格后。
要获得更好的控制效果,尤其是具有矛状的 Display
-和 ValueMembers
,可以进行切换到 Dictionary
或使用 List< someClass>
..
For better control, especially for having spearate Display
- and ValueMembers
you can switch to a Dictionary
or use a List<someClass>
..
这篇关于如何仅在一个数据单元中动态地在数据网格视图中添加一个组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!