C# DataGridViewComboBoxCell 绑定 - “值无效”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/654829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataGridViewComboBoxCell Binding - "value is not valid"
提问by Ian
I'm trying to bind separate ComboBox cells within a DataGridView to a custom class, and keep getting an error
我正在尝试将 DataGridView 中单独的 ComboBox 单元格绑定到自定义类,并不断收到错误消息
DataGridViewComboBoxCell value is not valid
DataGridViewComboBoxCell 值无效
I'm currently assigning the data source for the cell to an IList<ICustomInterface>
from a Dictionary I've got. Upon setting the data source however, the index for the ComboBoxCell
isn't set, so it has an invalid value selected.
我目前正在将单元格的数据源分配给IList<ICustomInterface>
我拥有的字典中的一个。但是,在设置数据源时,ComboBoxCell
未设置的索引,因此它选择了无效值。
I'm trying to figure out how to get it to select a real value, e.g. the 0th item within the list it has been given to remove this error, or find another way to solve the problem. Anyone have any suggestions?
我试图弄清楚如何让它选择一个真正的值,例如列表中的第 0 项已被赋予以消除此错误,或找到解决问题的另一种方法。有人有什么建议吗?
采纳答案by Ian
I managed to find the solution not long after posting the question. For anyone else:
发布问题后不久我设法找到了解决方案。对于其他人:
The problem was that I was trying to assign the DataGridViewComboBoxCell.Value
to an object, expecting that because the Cell was bound to a data source that it would automatically find the object in the source and update.
问题是我试图将 分配DataGridViewComboBoxCell.Value
给一个对象,期望因为 Cell 绑定到一个数据源,所以它会自动在源中找到该对象并进行更新。
This wasn't actually the case, you actually need to set the value equal to that of the ValueMember
property for it to correctly update the value and binding. I believe I was using a property 'Name' for both ValueMember
and DisplayMember
(controls how the renders in the cell) so setting the Value to interface.ToString()
(rather than the interface instance) works for the majority of cases. Then I catch and ignore any DataError exceptions that occur while I'm changing the source around.
实际情况并非如此,您实际上需要将值设置为等于ValueMember
属性的值才能正确更新值和绑定。我相信我是用属性“名称”两个ValueMember
和DisplayMember
(控制如何呈现在细胞),因此其值设置为interface.ToString()
(而不是接口实例),适用于大多数情况下。然后我捕获并忽略在更改源时发生的任何 DataError 异常。
回答by Ian
Afters hours of trials, I finally found a solution that works.
经过数小时的试验,我终于找到了一个有效的解决方案。
// Create a DataGridView
System.Windows.Forms.DataGridView dgvCombo = new System.Windows.Forms.DataGridView();
// Create a DataGridViewComboBoxColumn
System.Windows.Forms.DataGridViewComboBoxColumn colCombo = new
System.Windows.Forms.DataGridViewComboBoxColumn();
// Add the DataGridViewComboBoxColumn to the DataGridView
dgvCombo.Columns.Add(colCombo);
// Define a data source somewhere, for instance:
public enum DataEnum
{
One,
Two,
Three
}
// Bind the DataGridViewComboBoxColumn to the data source, for instance:
colCombo.DataSource = Enum.GetNames(typeof(DataEnum));
// Create a DataGridViewRow:
DataGridViewRow row = new DataGridViewRow();
// Create a DataGridViewComboBoxCell:
DataGridViewComboBoxCell cellCombo = new DataGridViewComboBoxCell();
// Bind the DataGridViewComboBoxCell to the same data source as the DataGridViewComboBoxColumn:
cellCombo.DataSource = Enum.GetNames(typeof(DataEnum));
// Set the Value of the DataGridViewComboBoxCell to one of the values in the data source, for instance:
cellCombo.Value = "Two";
// (No need to set values for DisplayMember or ValueMember.)
// Add the DataGridViewComboBoxCell to the DataGridViewRow:
row.Cells.Add(cellCombo);
// Add the DataGridViewRow to the DataGridView:
dgvCombo.Rows.Add(row);
// To avoid all the annoying error messages, handle the DataError event of the DataGridView:
dgvCombo.DataError += new DataGridViewDataErrorEventHandler(dgvCombo_DataError);
void dgvCombo_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
// (No need to write anything in here)
}
That is all.
就这些。
回答by Mark Jarzebowski
I had the same problem.
我有同样的问题。
In my case the solution was to fill the data adapter of the Foreign key table. This was not being automatically filled and this was the cause of the problem.
在我的情况下,解决方案是填充外键表的数据适配器。这不是自动填充的,这就是问题的原因。
In the Page_Load
Event:
在Page_Load
事件:
Me.TblUserTypesTableAdapter.Fill(Me.DonateDataSet.tblUserTypes)
回答by Carlos A merighe
I am having the same problem. After populating my ComboBox column in the (unbouod) DataGrid, I solved my problem by setting the ValueMember property of the DataGridViewComboBoxColumn
Apparently, just relying on the ToString()
property of the objects in the ComboBox is not enough.
我有同样的问题。在(unbouod)DataGrid 中填充我的 ComboBox 列后,我通过设置DataGridViewComboBoxColumn
Apparently的 ValueMember 属性解决了我的问题,仅依靠ToString()
ComboBox 中对象的属性是不够的。
Actual code:
实际代码:
/// <summary>
/// Populate the dataGridSplitVolumes data grid with all existing qualifications for the plan.
/// </summary>
/// <param name="bonus"></param>
private void PopulateDataGridSplitVolumes(Bonus_Group bonus)
{
try
{
List<Qualification> qualifications = Qualification.Load(this.groupBonus.PlanID, this.ConnectionString);
foreach (Qualification qual in qualifications)
{
DataGridViewComboBoxColumn col = (DataGridViewComboBoxColumn)this.dataGridSplitVolumes.Columns[0];
col.Items.Add(qual);
}
SplitVolumeGrid_QualificationColumn.ValueMember = "Name";
}
catch (Exception ex)
{
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
throw ex;
}
}//PopulateDataGridSplitVolumes
回答by Varo
Set a null value to the cell:
为单元格设置一个空值:
dataGridView.CurrentRow.Cells[NAME].Value = null;
回答by Sauleil
Here's my simple solution when using enums
这是我使用枚举时的简单解决方案
ColumnType.ValueType = typeof (MyEnum);
ColumnType.DataSource = Enum.GetValues(typeof (MyEnum));
you can do that just after "InitializeComponent();"
您可以在“InitializeComponent();”之后执行此操作
回答by SubqueryCrunch
For the sake of people not struggling as much as i did.
为了人们不像我那样挣扎。
When binding the combo you are setting a DisplayMember (what the user will see) and ValueMember (what your application will get).
绑定组合时,您正在设置 DisplayMember(用户将看到的内容)和 ValueMember(您的应用程序将获得的内容)。
After setting up these you need to set up the Value and this is where it fails. Basically the TYPE of the value needs to be the same TYPE as the ValueMember.
设置完这些后,您需要设置值,这就是失败的地方。基本上,值的 TYPE 需要与 ValueMember 的 TYPE 相同。
So if your value member is an ID obviously its of type INT and you need to set your value to int for example Cell.Value = 1;.
因此,如果您的值成员显然是 INT 类型的 ID,并且您需要将值设置为 int,例如 Cell.Value = 1;。
回答by Md Shahriar
use DataError Event handler,
使用 DataError 事件处理程序,
private void shahriartableDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//You don't have to write anything here !
}
and your DisplayMember and ValueMember data type should be the same, in my case I have CountryName for both. Everything works fine for me...!!
并且您的 DisplayMember 和 ValueMember 数据类型应该相同,在我的情况下,我有 CountryName 两者。对我来说一切正常......!
回答by GoTo
I was having the same problem. The message was 100% spot on. The values for the combobox were like: Exact, StartsWith... and I was trying to set the value Exact? (not Exact). This was happening automatically as I was reading the DataTable for the DataGridView from an .xml file with DataTable.ReadXml(...). The values in the .xml file were off.
我遇到了同样的问题。该消息是 100% 准确的。组合框的值类似于:Exact、StartsWith... 我试图设置值 Exact?(不准确)。这是在我使用 DataTable.ReadXml(...) 从 .xml 文件读取 DataGridView 的 DataTable 时自动发生的。.xml 文件中的值已关闭。
回答by KyleMit
Here's a complete example with a basic form and DataGridView
added via the designer:
这是一个带有基本表单的完整示例,并DataGridView
通过设计器添加:
Setup and bindings:
设置和绑定:
private void Form1_Load(object sender, EventArgs e)
{
var colors = new List<Code>()
{
new Code() {Value= "R", Text = "Red"},
new Code() {Value= "G", Text = "Green"},
new Code() {Value= "B", Text = "Blue"}
};
var users = new List<User>()
{
new User() {Name = "Briana", FavoriteColor = "B"},
new User() {Name = "Grace", FavoriteColor = "G"}
};
var colorCol = new DataGridViewComboBoxColumn();
colorCol.DataSource = colors;
colorCol.DisplayMember = "Text";
colorCol.ValueMember = "Value";
colorCol.DataPropertyName = "FavoriteColor";
dataGridView1.Columns.Add(colorCol);
dataGridView1.DataSource = users;
}
Some classes:
部分课程:
public class Code
{
public string Value { get; set; }
public string Text { get; set; }
}
public class User
{
public string Name { get; set; }
public string FavoriteColor { get; set; }
}