Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBox in DatagridView in Edit Mode

I have a DataGridView with read-only mode set to true (non-editable) which takes values from a database on form load. When I set the read-only mode to false (editable mode), I want a particular column (eg. Department) to visible as ComboBox so i can select values from there. And when i enter the Read-Only mode, the ComboBox should disappear and DataGridView should be visible as normal. How to achieve it? I am using C# framework 4.0, Winforms

like image 615
Sandy Avatar asked Sep 16 '11 17:09

Sandy


3 Answers

See the implementation at ComboBox with read only behavior.

You could also change the DisplayStyle based on when the readonly of the DataGridView property is changed. Setting the DisplayStyle to DataGridViewComboBoxDisplayStyle.Nothing will hide the drop down button.

For example, changing the ReadOnly property with a button click would look something like this:

private void mChangeReadOnlyButton_Click(object sender, EventArgs e)
{
   ComboBoxColumn2.DisplayStyle = (dataGridView1.ReadOnly) ?
      DataGridViewComboBoxDisplayStyle.ComboBox :
      DataGridViewComboBoxDisplayStyle.Nothing;
   dataGridView1.ReadOnly = !dataGridView1.ReadOnly;
}

Editable:

Editable

ReadOnly:

ReadOnly

like image 126
SwDevMan81 Avatar answered Nov 09 '22 17:11

SwDevMan81


I got the solution to my problem, just thought to post it here. On entering edit mode, running the following code may solve the problem.

public void bgCombo(DataGridView dg)
{
    foreach (DataGridViewRow row in dg.Rows)
    {
        DataGridViewComboBoxCell dgc = new DataGridViewComboBoxCell();
        dgc.Value = row.Cells["Department"].Value;
        row.Cells["Department"] = dgc;
    }
}

Before setting dgc to dataGridCell we can add items collections in it. Hope it helps.

PROBLEM: If the Column and Row index, becomes same while editing, i am getting an error - Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function.

like image 42
Sandy Avatar answered Nov 09 '22 17:11

Sandy


If you want to hide a combobox for selected rows you can use the DataGridViewComboBoxDisplayStyle property

The options are ComboBox, DropdownBox or None

In the example - only display the ComboBox in column 4 if there is a value in column 2

For Each row As DataGridViewRow In dgv.Rows  
        Dim Cell As DataGridViewComboBoxCell = CType(row.Cells(4), DataGridViewComboBoxCell)  
    Cell.ReadOnly = True  
    Cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing  
    If row.Cells(2).Value IsNot Nothing Then  
        Cell.ReadOnly = False  
        Cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox  
    End If  
Next
like image 1
andybrum Avatar answered Nov 09 '22 15:11

andybrum