3

我有一个数据绑定 DataGridView。它的列之一是 DataGridViewComboBox。DataGridViewComboBox 也是数据绑定的。一切正常,直到我希望检索 DataGridViewComboBox选定项后面的 DataRow (不是 DataGridView 的 DataRow,而是填充组合框的 DisplayMember 和 ValueMember 的数据行!)。

我怎样才能做到这一点?我需要这个,因为我需要在 DisplayMember 和 ValueMember 旁边显示一大堆数据,并且这些数据存在于 DataGridViewComboBox 绑定到的 DataTable 的数据行中。

提前感谢您的帮助。

丹尼尔

4

1 回答 1

1

This is detailed in this MSDN article.

What you need to do is set the ValueMember of the ComboBox column to a property that returns a reference to the business object itself.

That is, say you have an Employee object, and a list of them are the DataSource for the ComboBox column. Employee would perhaps look like this:

public Employee
{
    int Age { get; set; }
    string Name { get; set;}
    Employee Self
    {
        get { return this; }
    }
} 

Then you create your ComboBox columns like so:

DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = "Combo";
col.ValueMember = "Self";
col.DisplayMember = "Name";
datagridview1.Columns.Add(col);

Then when you retrieve the Value property of a ComboBox cell you get an Employee object back:

Employee e = datagridview1.Rows[0].Cells["Combo"].Value as Employee;
于 2011-10-17T09:28:50.757 回答