我在Windows窗体应用程序中有一个datagridview。 datagridview有3列。第一列是Combobox。 我正在尝试将项目添加到组合框但它正在工作。 这是代码(语言C#)
foreach (int counter=0; counter<5; counter++ )
{
this.dataGridView1.Rows.Add();
DataGridViewComboBoxCell cbCell = new DataGridViewComboBoxCell();
cbCell.Items.Add("Male");
cbCell.Items.Add("Female");
dataGridView1.Rows[counter].Cells[0] = cbCell;
dataGridView1.Rows[counter].Cells[1].Value = firstname[counter];
dataGridView1.Rows[counter].Cells[2].Value = lastname[counter];
}
网格显示5行。但是第一个组合框列在每个组合框中都没有项目。
请帮忙。 感谢。
答案 0 :(得分:1)
由于代码没有显示列的构造方式,因此很难分辨出问题所在,但代码未使用DataGridViewComboBoxColum
。只需DataGridViewComboBoxColumn
就可以使第0列中的每一行都成为具有“男性”,“女性”选择的组合框。
格式错误的foreach
循环不正确,无法编译。我假设你正在寻找一个for
循环。在此for
循环之后......新行正确添加到网格中。然后创建一个新的DataGridViewComboBoxCell
并添加当前行的单元格[0]。 dataGridView1.Rows[counter].Cells[0] = cbCell;
。此单元格[0]将添加到每个新行。
如果DataGridViewViewComboBoxColumn
设置正确,则无需这样做。添加DataGridViewComboBoxCell
是完全有效的,基本上允许您将组合框放入任何“SINGLE”单元格。然而,如果使用这种方式使组合框的使用本身有问题。
循环是将数据“添加”到dataGridView1
。当您阅读数据时,关于“性别”(男性,女性)的部分似乎缺失,因此未将值设置为其他值。示例:没有如下所示的行:
dataGridView1.Rows[counter].Cells[0].Value = gender[counter];
如果有一个“Gender”数组保存此信息,那么当代码在组合框列上方的代码行中设置此值(男性,女性)时,将自动将组合框选择设置为该值。数据只是两个值中的“一”(1)。
因此,假设您正在寻找此代码,下面的代码演示了如何使用DataGridViewComboBoxColumn
将数据读入组合框单元时要小心;如果组合框列的字符串数据与组合框项目列表中的某个项目不匹配,则代码将在未捕获和解决时崩溃。如果值为空字符串,则组合框将所选值设置为空。
// Sample data
string[] firstname = { "John", "Bob", "Cindy", "Mary", "Clyde" };
string[] lastname = { "Melon", "Carter", "Lawrence", "Garp", "Johnson" };
string[] gender = { "Male", "", "Female", "", "Male" };
// Create the combo box column for the datagridview
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.Name = "Gender";
comboCol.HeaderText = "Gender";
comboCol.Items.Add("Male");
comboCol.Items.Add("Female");
// add the combo box column and other columns to the datagridview
dataGridView1.Columns.Add(comboCol);
dataGridView1.Columns.Add("FirstName", "First Name");
dataGridView1.Columns.Add("LastName", "Last Name");
// read in the sample data
for (int counter = 0; counter < 5; counter++ )
{
dataGridView1.Rows.Add(gender[counter], firstname[counter], lastname[counter]);
}
希望这有帮助。