首页 文章

DataGridView使用ComboBox绑定到DataTable

提问于
浏览
2

我有DataGridView dgvData,它有两列 .

1列是DataGridViewComboBoxCell的类型,我将此列链接到人员的DataSource .

人们有名称和ID属性,因此,我将第一列ValueMember作为“ID”,将DisplayMember作为“名称” .

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

我希望绑定将PeopleName与我的DataGridView的第一列匹配,并将CallPhone绑定到我的DataGridView中的第二列 .

在此之后,我希望当我在我的整个DataGridView上循环以仅查找我的第一列的值时,我的意思是人员的ID(来自第1列的数据源 - 人员)

你能帮帮我们吗?

1 回答

  • 6

    我们假设以下数据库设置:

    ╔════════════════════════════╗    ╔═════════════════════════════════╗
    ║          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" 与来自 peopleDataGridViewComboBoxColumn 一致,您必须设置 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

相关问题