如何在DatagridviewComboboxColumn Cell中选择值

时间:2014-12-18 13:03:08

标签: c# datagridview

我有一个datagridview,其中包含一个我想要的Combobox列,当我从组合框中选择一个添加值时,它会显示一个新表单。我试过这段代码,但它不起作用:

private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            switch (dataGridView2.Columns[e.ColumnIndex].Name)
            {
                case "CategorieDataGridViewTextBoxColumn":

                    if (dataGridView2.Rows[e.RowIndex].Cells["CategorieDataGridViewTextBoxColumn"].Value.ToString() == "Add")
                    {
                        Categorie cat = new Categorie();
                        cat.Show();

                    }

                    break;
            }

        }

那我怎么办呢?

1 个答案:

答案 0 :(得分:3)

您应该在DataGridView单元格中的ComboBox中更改值时处理该事件。试试这个代码,它将触发dataGridView中的comboBox中的选择事件:

public Form1()
    {
        InitializeComponent();

        DataGridViewComboBoxColumn cmbcolumn = new DataGridViewComboBoxColumn();
        dataGridView2.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView2_EditingControlShowing);


    }

    private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        ComboBox combo = e.Control as ComboBox;
        if (combo != null)
        {
            combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
            combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
        }
    }

    private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox cb = (ComboBox)sender;
        string item = cb.Text;
        if (item == "Add")
        {
            Categorie cat = new Categorie();
            cat.Show();

        }
    }