C# 如何在DataGridView中选择Combobox值

C# 如何在DataGridView中选择Combobox值,c#,datagridviewcolumn,C#,Datagridviewcolumn,我在DataGridView中有3列 文本类型 组合框 文本类型 我将Datagridview的Combobox绑定如下: BindingSource bindingSourceUnit = new BindingSource(); bindingSourceUnit.DataSource = datatableObject; ColumnUnit.DataSource = bindingSourceUnit; ColumnUnit.ValueMember = "id"; ColumnUnit

我在DataGridView中有3列

文本类型 组合框 文本类型 我将Datagridview的Combobox绑定如下:

BindingSource bindingSourceUnit = new BindingSource();
bindingSourceUnit.DataSource = datatableObject;

ColumnUnit.DataSource = bindingSourceUnit;
ColumnUnit.ValueMember = "id";
ColumnUnit.DisplayMember = "title";
这将显示组合框第二列每行中的所有项目。 现在,我正在从数据库获取数据,并希望在DataGridView中显示它

在while循环中,ColumnUnit是我的ComboboxType字段。它不允许我预先选择值


如何设置此列的值?

您使用的是Ajax组合框控件还是标准复选框列表控件

在任何情况下,您都需要告诉控件应该选择哪个组合值,因此必须进行检查,查看从数据库调用返回的值,然后在组合框值列表中搜索该值,当找到正确的值时,将selected属性设置为true

试一试

尝试将单元格强制转换为DataGridViewComboxCell,您应该能够以这种方式更改值

var tempCombo = (DataGridViewComboBoxCell)drNew.Cells[0].Value;

也许不是最好的解决方案:

private void dataGridView1_DefaultValuesNeeded(object sender,
    System.Windows.Forms.DataGridViewRowEventArgs e)
{
    e.Row.Cells["ColumnUnit"].Value = ... ; // set default value here
}

我使用的是C Windows窗体,在combobox中会有显示和值,所以我将从数据库中获取值,基于值我想选择combobox值我已经尝试了上面的代码,既没有选择combobox值,也没有错误。Try-var tempCombo=DataGridViewComboBoxCelldrNew.Cells[0]。Value;我已经将其添加到post中,您是否使用了调试器来逐步执行代码并计算行的值。。您究竟在克隆什么或试图克隆什么..我在示例中看到,如果您想在网格中显示数据,您必须克隆行以便它可以包含所有列,或者您必须在每次从select查询中获取数据时手动添加行。。执行查询后,使用Fill方法返回数据,并通过datatable或dataset将结果绑定到datagrid。。
var tempCombo = (DataGridViewComboBoxCell)drNew.Cells[0].Value;
private void dataGridView1_DefaultValuesNeeded(object sender,
    System.Windows.Forms.DataGridViewRowEventArgs e)
{
    e.Row.Cells["ColumnUnit"].Value = ... ; // set default value here
}