2017-01-12 41 views
0

我在Windows窗体应用程序中有一个datagridview。 datagridview有3列。第一栏是Combobox。 我想将项目添加到组合框,但它工作。 下面是代码(语言C#)将项目添加到已存在的datagridview组合框列中的组合框中

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行。但是第一个组合框列在每个组合框中都没有项目。

请帮忙。 谢谢。

回答

1

由于代码并未显示如何构建列,因此很难说出问题所在,但代码未使用DataGridViewComboBoxColumDataGridViewComboBoxColumn是您需要使第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]; 

如果有一个“性别”阵列保持此信息,则当代码中的代码组合上面的行设置该值(男,女)框中的列将自动将组合框选择设置为该值。数据将只是这两个值中的“一个”(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]); 
} 

希望这会有所帮助。

+0

非常感谢JohnG –