由于代码没有显示列的构造方式,因此很难判断问题可能是什么,但是代码没有使用DataGridViewComboBoxColum。 DataGridViewComboBoxColumn 是您只需将第 0 列中的每一行都设置为包含“男性”、“女性”选项的组合框。
格式错误的foreach 循环不正确,无法编译。我假设 for 循环是您正在寻找的。在这个for 循环之后……一个新行被正确地添加到网格中。然后创建一个新的DataGridViewComboBoxCell 并添加当前行的单元格[0]。 dataGridView1.Rows[counter].Cells[0] = cbCell;。这个单元格[0] 被添加到每个新行中。
如果DataGridViewViewComboBoxColumn 设置正确,这是不必要的。添加DataGridViewComboBoxCell 是完全有效的,基本上允许您将组合框放入任何“单个”单元格中。但是,如果以这种方式使用,组合框本身的使用就会产生问题。
循环将数据“添加”到dataGridView1。当您阅读数据时,似乎缺少有关“性别”(男性,女性)的部分,因此该值未设置为其他值。示例:没有像下面这样的一行:
dataGridView1.Rows[counter].Cells[0].Value = gender[counter];
如果存在保存此信息的“性别”数组,那么当代码在组合框列上方的代码行中设置此值(男性、女性)时,将自动将组合框选择设置为该值。数据将只是两个值中的“一”(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]);
}
希望这会有所帮助。