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
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:
ReadOnly:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With