2015-09-03 71 views
2

我有DataGridView dgvData,它有两列。DataGridView绑定到DataTable与组合框

1列是DataGridViewComboBoxCell的类型,我将此列与人员的DataSource关联。

人们拥有名称和ID属性,因此,我将第一列ValueMember设置为“ID”,将DisplayMember设置为“Name”。

现在,我想将DataTable链接到DataGridView。 DataTable有2列,PeopleName和PeopleCallPhone。

我想绑定将PeopleName匹配到我的DataGridView的第一列,并将CallPhone绑定到我的DataGridView中的第二列。

在此之后,我当我在循环我的整个的DataGridView找到我的第一纵队才值想要的,我指的是人的ID(从第1列的数据源 - 人)

你能帮助我吗?

+0

请澄清你的类型:'People.ID'是'int','People.Name'是'string','PeopleName'是'字符串(匹配'People.Name')和'PeopleCallPhone'是什么? – OhBeWise

+0

有些字符串,与People类无关。 –

回答

5

假设以下数据库设置:

╔════════════════════════════╗ ╔═════════════════════════════════╗ 
║   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"; 

结果:

Working example

关于你的第二个问题,找到每个项目的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); 
     } 
    } 
} 

输出:

Console output