将不同的项添加到DataGridView中每行的DataGridViewComboBoxColumn

时间:2018-05-22 19:13:05

标签: c# winforms datagridview

enter image description here

假设我的申请中有DataGridView    - Child是一个组合框列
   - ChildID是一个组合框列

我有一些名为Table的对象,我想在Child - 列中加载。每个Table对象都有一些Column个对象,我想在ChildID - 列中加载。

当我更改Child组合框时,ChildID列应自动更改为从Table对象加载相应的列。

以下代码是我的尝试:

            // populate the DataGridView
            if (database != null)
            {
                childDataGridView1Column1.Items.Clear();
                dataGridView1.Rows.Clear();

                string firstTableName = database.Tables[0].Name;

                // Loading ComboBox columns              
                int i = 0;
                foreach (Table t in database.Tables)
                {
                    dataGridView1.Rows.Add(true, t.Name, t.PrimaryKeyName);//Set Child's text to "None"
                    dataGridView1.Rows[i].Tag = t;

                    // Load 'Database.Tables' to 'Child' column
                    DataGridViewComboBoxCell dataGridview1ChildComboBoxCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[(int)CellNo.Child];
                    dataGridview1ChildComboBoxCell.Items.Clear();
                    foreach (Table t2 in database.Tables)
                    {
                        dataGridview1ChildComboBoxCell.Items.Add(t2.Name);
                    }
                    dataGridView1.Rows[i].Cells[(int)CellNo.Child].Value = firstTableName;

                    // Load 'Table.Columns' to 'ChildID' column
                    DataGridViewComboBoxCell dataGridview1ChildIDComboBoxCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[(int)CellNo.ChildID];
                    dataGridview1ChildIDComboBoxCell.Items.Clear();
                    foreach (Column c in t.Columns.Values)
                    {
                        dataGridview1ChildIDComboBoxCell.Items.Add(c.Name);
                    }

                    i++;
                }
            }

    ... ... ...   

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        //DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[(int)CellNo.Child];
        //if (cb.Value != null)
        {
            // do stuff
            DataGridViewRow row = dataGridView1.SelectedRows[0];
            Table t = row.Tag as Table;

            // Load 'Table.Columns' to 'ChildID' column
            DataGridViewComboBoxCell dataGridview1ChildIDComboBoxCell = (DataGridViewComboBoxCell)row.Cells[(int)CellNo.ChildID];
            dataGridview1ChildIDComboBoxCell.Items.Clear();
            foreach (Column c in t.Columns.Values)
            {
                dataGridview1ChildIDComboBoxCell.Items.Add(c.Name);
            }

            dataGridView1.Invalidate();
        }
    }

但是,它不起作用。

0 个答案:

没有答案
相关问题