Home > front end >  C# Convert DatagridViewTextbox to DataGridViewComboBoxCell
C# Convert DatagridViewTextbox to DataGridViewComboBoxCell

Time:11-18

I have a DataGridView table that is already filled. Now, when I click on a cell in the DataGridView, I want to make a ComboBox out of the cell, where I can then choose a selection of "Items".

Dgv_Data_List is my DataGridView.

        private void Dgv_Data_List_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
            DataGridViewComboBoxCell CboCell = new DataGridViewComboBoxCell();
            CboCell.Items.AddRange("Yes", "No");
            Dgv_Data_List.Rows[e.RowIndex].Cells[e.ColumnIndex] = CboCell;  <--At this point my program crashes
    }

I don't want any fixed comboboxes. They should be created at runtime as soon as they are needed.

CodePudding user response:

It is unclear how the grid is filled with data. You may get away with this if the columns and rows are manually added, however if the grid has a DataSource, then when you “double-click” into a cell and set the cell as a combo box as you show… then the “current” cells value better be a “Yes” or “No” or you will get the grids DataError complaining about the value in the cell not being a valid combo box value.

I would think you would have to “delete” the current cells value just to avoid the possible error. Something like…

DataGridViewComboBoxCell CboCell = new DataGridViewComboBoxCell();
CboCell.Items.AddRange("Yes", "No");
Dgv_Data_List.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
Dgv_Data_List.Rows[e.RowIndex].Cells[e.ColumnIndex] = CboCell;

Setting the cells value to a blank string will work. HOWEVER, if the column type of the cells underlying data source is of a numeric type… then you will get the grids DataError complaining that the “Yes” or “No” value is not a valid numeric value… so technically this will ONLY work if the column type is a string type column. As most of this is unknown, I can only assume ALL the cells are of a string type.

CodePudding user response:

As the code given, you created comboboxcell but not convert the grid view. so do this instead.

this.dataGridView1[CboCell] = new DataGridViewComboBoxCell();

Try this in the place of creating the comboboxcell.

  • Related