【问题标题】:DataGridViewComboBoxCell value is not valid #2DataGridViewComboBoxCell 值无效 #2
【发布时间】:2015-06-18 02:57:56
【问题描述】:

我知道这可能是重复的,但我无法找到有效的解决方案。我有一个具有组合框列的 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);

 }

如何设置组合框的值??

【问题讨论】:

  • 我不明白微软为什么把这件事弄得这么难!

标签: c#


【解决方案1】:

在这个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();
}

【讨论】:

    猜你喜欢
    • 2014-07-21
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多