Gridview - convert textboxcell to comboboxcell and back

狂风中的少年 提交于 2020-01-07 02:35:28

问题


I have a question about datagridviewcell. i have created textboxcolumn in datagridview. when ever i click the particular cell the cell should change to datagridviewcomboboxcell. Also i need to add the item in combobox collection. when i go to another cell then, the new cell get datagridviewcombobox cell and existing cell should change to datagridviewtextbox cell...


回答1:


You could change the DataGridViewTextBoxCell to DataGridViewComboBoxCell in the CellBeginEdit event and change it back in CellEndEdit event.

Try this:

        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 
        }


来源:https://stackoverflow.com/questions/6533976/gridview-convert-textboxcell-to-comboboxcell-and-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!