Gridview - 将textboxcell转换为comboboxcell并返回

时间:2011-06-30 11:25:46

标签: winforms c#-4.0 .net-4.0

我对datagridviewcell有疑问。 我在datagridview中创建了textboxcolumn。当我点击特定的单元格时,单元格应该更改为datagridviewcomboboxcell。此外,我需要在组合框集合中添加项目。 当我去另一个单元格时,新单元格获取datagridviewcombobox单元格,现有单元格应该更改为datagridviewtextbox单元格...

1 个答案:

答案 0 :(得分:1)

您可以在DataGridViewTextBoxCell事件中将DataGridViewComboBoxCell更改为CellBeginEdit,然后在CellEndEdit事件中将其更改回来。

试试这个:

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {   DataGridViewComboBoxCell cb=new DataGridViewComboBoxCell();
            cb.Items.Add(dataGridView1.CurrentCell.Value);
            //add your other itmes here;
            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = cb;//change the DataGridViewTextBoxCell to DataGridViewComboBoxCell 
        }

        delegate void settexthandler(DataGridViewCellEventArgs e); //use delegate to prevent reentrant call 

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView1.BeginInvoke(new settexthandler(settoTextBox), new object[] { e });           
        }

        void settoTextBox(DataGridViewCellEventArgs e)
        {
            DataGridViewTextBoxCell tb = new DataGridViewTextBoxCell();

            tb.Value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = tb; //set it back to DataGridViewTextBoxCell with newly selected value 
        }