DataGridViewComboBoxCell值无效#2

时间:2015-06-17 16:02:53

标签: c#

我知道这可能是重复的,但我找不到有效的解决方案。我有一个具有组合框列的datagridview。当我没有尝试设置组合框列的值时,一切都很好(即,组合框列正在填充)。当我尝试设置值时,我得到臭名昭着的" DataGridViewComboBoxCell值无效"错误。这是我的代码:

//Retrieve Data
System.Data.DataRowCollection DR1 = GetData(constants.SQL_1);
System.Data.DataRowCollection DR2 = GetData(constants.SQL_2);

//Populate list for combo box column
List<string> list2 = new List<string>();
foreach (System.Data.DataRow DR in DR2)
    list2 .Add(DR["fieldname"].ToString().Trim());

//Set datasource of combo box column
DataGridViewComboBoxColumn cmb =   (DataGridViewComboBoxColumn)dgv.Columns["comboboxcolumnname"];
cmb.ValueType = typeof(string);
cmb.DataSource = list2 ;

//Populate Data Grid View
foreach (System.Data.DataRow DR in DR1)
{

    DataGridViewComboBoxCell cell = new DataGridViewComboBoxCell();
    cell.Value = DR["fieldname"].ToString();

    DataGridViewRow row = new DataGridViewRow();

    row.Cells.Add(cell);
    dgv.Rows.Add(row);

 }

如何设置组合框的值??

1 个答案:

答案 0 :(得分:0)

在这个Post中,它建议根本不设置组合框列的数据源属性。所以这就是我所做的:

System.Data.DataRowCollection DRC1 = dictionaries.GetData(constants.SQL_1);
System.Data.DataRowCollection DRC2 = dictionaries.GetData(constants.SQL_2);

foreach (System.Data.DataRow DR1 in DRC1)
{
     DataGridViewComboBoxCell cmb = (DataGridViewComboBoxCell)dgv[0, dgv.Rows.Count - 1];

     foreach (System.Data.DataRow DR2 in DRC2)
     {
         cmb.Items.Add(DRC2["fieldname2"].ToString().Trim());
     }

     cmb.Value = DRC1["fieldname1"].ToString();
}