组合框未在C#中的DataGridView中显示默认值

时间:2011-07-21 09:52:12

标签: c# winforms datagridview combobox

我正在尝试允许用户为每个新行选择DataGridViewComboBoxColumn的值。我已将ComboBox GridView绑定到数据库,但每当我输入新行时,我都会看到DataGridViewComboBoxColumn没有初始值。我必须先设置值。

每当我在DataGridViewComboBoxColumn中输入新行时,如何在DataGridView中显示默认值?

这就是我将DataGridView ComboBox绑定到数据库的方式:

bindingSource1.DataSource = itemBAL.GetTable();
dataGridView1.DataSource = bindingSource1; 
ItemName.DataSource = bindingSource1; //Where ItemName is an instance ofDataGridViewComboBoxColumn
ItemName.DisplayMember = "Name";
ItemName.ValueMember = "ItemId";

3 个答案:

答案 0 :(得分:7)

您可以使用组合框列的DefaultCellStyle.NullValueDefaultCellStyle.DataSourceNullValue属性。

关于此here,有一篇非常全面的MSDN文章。

我还给出了一个代码示例:

// Let's say I have this list of cars I want to add to my datagridview
List<Car> cars = new List<Car>();
cars.Add(new Car() { Index = 0, Make = "Ford" });
cars.Add(new Car() { Index = 1, Make = "Chevvy" });
cars.Add(new Car() { Index = 2, Make = "Toyota" });

// I create the column, setting all the various properties
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.DataSource = cars;
col.Name = "Cars";
col.DisplayMember = "Make";
col.HeaderText = "Car";
col.ValueMember = "Index";
col.DataPropertyName = "Car";

// As well as standard properties for a combobox column I set these two:
col.DefaultCellStyle.NullValue = cars[0].Make;
col.DefaultCellStyle.DataSourceNullValue = cars[0].Index;

dataGridView1.Columns.Add(col);

dataGridView1.DataSource = dt;

上面的代码需要注意的一点是,我将DataPropertyName设置为允许与datagridview的数据源上的属性绑定。

如果我没有这样做,那么当用户没有选择任何内容时,我需要在访问组合框列时添加一些额外的逻辑,因为属性的值将为null(NullValue不会将值设置为实际值)单元格,仅显示默认值。)

答案 1 :(得分:2)

bindingSource1.DataSource = itemBAL.GetTable();
dataGridView1.DataSource = bindingSource1; 
ItemName.DataSource = bindingSource1; //Where ItemName is an instance ofDataGridViewComboBoxColumn
ItemName.DisplayMember = "Name";
ItemName.ValueMember = "ItemId";

仅添加此行

dataGridView1["ItemName",dataGridRowNumber].value=1;//item id value

答案 2 :(得分:0)

您可以在设计师或代码中向DataGridViewComboBoxColumn添加项目。

相关问题