问题描述
我试图让用户从 DataGridViewComboBoxColumn
中为每个新行选择值.我已将 GridView
中的 ComboBox
绑定到数据库,但是每当我输入新行时,我都会看到没有初始值的 DataGridViewComboBoxColumn
.我必须先设置值.
I'm trying to allow user to select value from DataGridViewComboBoxColumn
for each new row. I've bound ComboBox
in GridView
to database, but whenever I enter new row I see DataGridViewComboBoxColumn
with no initial value. I have to set the value first.
每当我在 DataGridView
中输入新行时,如何让默认值出现在 DataGridViewComboBoxColumn
中?
How can I let default value appear in DataGridViewComboBoxColumn
whenever I enter new row in DataGridView
?
这就是我如何将 DataGridView
ComboBox
绑定到数据库:
This is how I'm binding DataGridView
ComboBox
to database :
bindingSource1.DataSource = itemBAL.GetTable();
dataGridView1.DataSource = bindingSource1;
ItemName.DataSource = bindingSource1; //Where ItemName is an instance ofDataGridViewComboBoxColumn
ItemName.DisplayMember = "Name";
ItemName.ValueMember = "ItemId";
推荐答案
您可以使用组合框列的 DefaultCellStyle.NullValue
和 DefaultCellStyle.DataSourceNullValue
属性.
You can use the DefaultCellStyle.NullValue
and DefaultCellStyle.DataSourceNullValue
properties of the combo box column.
我还在下面给出了一个代码示例:
I've also given a code example below:
// 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 数据源上的属性绑定.
One thing to note with the code above is that I am setting the DataPropertyName
to allow binding with a property on the datagridview's datasource.
如果我没有这样做,那么当用户没有选择任何内容时,我将需要在访问组合框列时添加一些额外的逻辑,因为属性的值将为空(NullValue 未将值设置为实际单元格,只显示默认值).
If I was not doing that then I would need to add some additional logic when accessing the combo box column when users have selected nothing, since the Value of the property would be null (the NullValue does not set a value to the actual cell, only shows a default value).
这篇关于组合框未在 C# 中的 DataGridView 中显示默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!