将默认值设置为DataGridViewComboBoxCell

时间:2010-03-01 17:23:59

标签: c# datagridview datagridviewcomboboxcell

组合框默认显示一个空白字段,即使组合框中填充了多个值

ColumnSpeed.DataSource = speedList;
ColumnSpeed.ValueType = typeof(string);

我也尝试了以下内容,但它仍然显示空白文本。

foreach (DataGridViewRow row in myDataGridView.Rows)
{
    DataGridViewComboBoxCell cell = row.Cells[ColumnSpeed.Index] as DataGridViewComboBoxCell;
    if (cell != null)
    {
        cell.DataSource = speedList;
        cell.Value = cell.Items[0].ToString();
    }   
}

3 个答案:

答案 0 :(得分:0)

您分配给DataGridView的ValueMember可能与您指定的DisplayMember不同。如果是这种情况,你会得到一个空白值,而且你会得到一个DataGridError。

你应该尝试:

foreach (DataGridViewRow row in dgMain.Rows){
DataGridViewComboBoxCell pkgBoxCell = row.Cells[ColumnSpeed.Index]

pkgBoxCell.Value = ((Package) pkgBoxCell.Items(0)).Id

}

我从vb.net转换了它,所以它可能无法编译。代替我设置值的行,执行检索和设置正确的ValueMember值所需的任何步骤。在我的示例中,我将项目转换为特定类型并使用它的id。

答案 1 :(得分:0)

我相信你写的代码应该有效..只是想知道你在哪里调用相同的代码。如果在网格的数据绑定完成事件中调用它,它应该可以工作

答案 2 :(得分:0)

设置完所有DataSource后,尝试调用DataGridView.Refresh()方法。通常需要显示对DataSource的更改。