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

问题描述:

我试图让用户从每个新行的DataGridViewComboBoxColumn中选择值。我已将ComboBoxGridView绑定到数据库,但每当我输入新行时,我都会看到DataGridViewComboBoxColumn没有初始值。我必须先设定值。组合框在DataGridView中不显示默认值C#

每当我在DataGridView中输入新行时,如何让默认值出现在DataGridViewComboBoxColumn

这是我如何结合DataGridViewComboBox数据库:

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

可以在设计或代码项目添加到您的DataGridViewComboBoxColumn

您可以使用组合框列的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的DataSource属性绑定。

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

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