让我们假设以下数据库设置:
╔════════════════════════════╗ ╔═════════════════════════════════╗
║ People ║ ║ Your DataTable Info ║
╠════╦═══════════════════════╣ ╠═══════════════╦═════════════════╣
║ ID ║ Name ║ ║ PeopleName ║ PeopleCallPhone ║
╠════╬═══════════════════════╣ ╠═══════════════╬═════════════════╣
║ 1 ║ "John Smith" ║ ║ "John Smith" ║ 123-456-7890 ║
║ 2 ║ "Jane Doe" ║ ║ "Jane Doe" ║ 234-567-8900 ║
║ 3 ║ "Foo Bar" ║ ║ "Foo Bar" ║ 345-678-9000 ║
║ 4 ║ "Justin Time" ║ ║ "Justin Time" ║ 456-789-0000 ║
║ 5 ║ "Imma Mann" ║ ║ "Imma Mann" ║ 567-890-0000 ║
╚════╩═══════════════════════╝ ╚═══════════════╩═════════════════╝
另外,让我们假设您的数据结构是:
List<People> people = GetPeopleFromDB();
DataTable table = GetDataTableInfoFromDB();
为了使DataTable 列"PeopleName" 与源自people 的DataGridViewComboBoxColumn 一致,您必须设置DataGridViewComboBoxColumn.DataPropertyName。因为DataTable 列中的值与People.Name 匹配,所以这是您必须在DataGridViewComboBoxColumn.ValueMember 上设置的属性。例如:
var col = new DataGridViewComboBoxColumn();
col.Name = "PeopleName";
col.DataPropertyName = "PeopleName"; // The DataTable column name.
col.HeaderText = "Name";
col.DataSource = people;
col.DisplayMember = "Name";
col.ValueMember = "Name"; // People.Property matching the DT column.
this.dataGridView1.Columns.Add(col);
this.dataGridView1.DataSource = table;
this.dataGridView1.Columns[1].HeaderText = "Phone";
结果:
至于您的第二个问题,要在遍历每一行时找到每个条目的 ID,您首先要获取 ComboBoxColumn 的源。然后,您可以遍历每一行并使用第一列中的值,在源中找到与该值关联的 ID。例如:
List<People> ppl = ((DataGridViewComboBoxColumn)this.dataGridView1.Columns[0]).DataSource as List<People>;
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (row.Index != this.dataGridView1.NewRowIndex)
{
var cell = row.Cells[0] as DataGridViewComboBoxCell;
People person = ppl.SingleOrDefault(p => p.Name == cell.Value.ToString());
if (person != null)
{
Console.WriteLine("{0} {1}, {2}", person.ID, person.Name, row.Cells[1].Value);
}
}
}
输出: