日期:2014-05-20  浏览次数:20983 次

DataGridView中两个DataGridViewComboBoxColumn联动问题
在DataGridView中有三列,c1,c2,c3。 
c1和c2是DataGridViewComboBoxColumn模式,c3是DataGridViewTextBoxColumn模式 
1、从数据库表A中选择一列数据添加到c1的一个单元格中,点击下拉框可以列出所有数据。 
2、在c1选择一条数据后,c2根据c1的内容从数据库表B中选择一列数据添加到单元格中。 
3、同样,在c2选择一条数据后,c3根据c2的内容从数据库表C中选择对应的唯一值显示出来。

我要经过测试正常的可运行完整代码,联动正常不报错。数据库表可手动构建DataTable放入测试数据。网上找的资料不是联动出错就是DataGridViewComboBoxCell值无效问题。。。

------解决方案--------------------
关键代码Grid
C# code


   private void dgvNeed_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                ChoosePart cp = new ChoosePart();
                //this.Visible = false;
                cp.ShowDialog();
                //在这动态绑定一下就哦了。。 dgvNeed.Rows[e.RowIndex].Cells[e.ColumnIndex].Value =XXX ;
                if (cp.flag)
                {
                    dgvNeed.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = cp.selectedPart.Name;
                   ...
                }

            }


        }

------解决方案--------------------
参考:http://topic.csdn.net/u/20090412/15/eb6cde5b-e713-49c0-8a11-2e37ab74189b.html

感觉对DataGridViewComboBoxCell操作挺难的, 干脆你自己在DataGridView上添加Combox控件, 直接对Combox控件操作好了.
------解决方案--------------------
显然这里 用模板列 更OK!

SelectionChangeCommitted事件 里面 有重新对 combobox2 数据绑定?
------解决方案--------------------
DataTable dtB;
private void button2_Click(object sender, EventArgs e)
{
this.dataGridView1.CellValueChanged +=
new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged_1);

DataTable dtA = GetDataTable("A");
this.Column1.DataSource = dtA.DefaultView; // Column1, Column2, Column3分别对应DataGridView的三个列
this.Column1.DisplayMember = "A表列1";

dtB = GetDataTable("B");
this.Column2.DataSource = dtB.DefaultView;
this.Column2.DisplayMember = "B表列2";
}
private void dataGridView1_CellValueChanged_1(object sender, DataGridViewCellEventArgs e)
{
if (this.dataGridView1.CurrentRow == null || this.dataGridView1.CurrentCell.Value == null)
return;

switch (this.dataGridView1.CurrentCell.ColumnIndex)
{
case 0:
DataRow dr = dtB.Select("B表列1='" + this.dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'")[0];

DataGridViewComboBoxCell dgc = (DataGridViewComboBoxCell)this.dataGridView1.CurrentRow.Cells[1];
dgc.Value = dr[1];

this.dataGridView1.CurrentRow.Cells[2].Value = dr[2];
break;
case 1:
this.dataGridView1.CurrentRow.Cells[2].Value =
dtB.Select("B表列2='" + this.dataGridView1.CurrentRow.Cells[1].Value.ToString() + "'")[0][2];
break;
}
}
private DataTable GetDataTable(string str)
{
DataTable dt = new DataTable(str);
dt.Columns.Add(str + "表列1");
dt.Columns.Add(str + "表列2");
dt.Columns.Add(str + "表列3");

for (int i = 0; i < 3; i++)
dt.Rows.Add(string.Format("行{0}", i),
string.Format("{0}之行{1}", str, i),
string.Format("{0}之值{1}", str, i));
return dt;