Reputation:
I am using a DataGridView control for displaying some data. I need to enable some data and disable some data dynamically based on some values in the grid.
Can anyone tell me how to do it?
Upvotes: 28
Views: 81171
Reputation: 1
type form load : -
For i = 0 to Datagridview.columns.count -1
if i <> 1 then //restricted columns, 'i' is Your column index
Datagridview.Columns(i).ReadOnly = True
end if
Next
type Cellbeginedit
Datagridview.BeginEdit(True)
Upvotes: 0
Reputation: 2019
To "disable" a cell, it must be read-only and grayed out somehow. This function enables/disables a DataGridViewCell:
/// <summary>
/// Toggles the "enabled" status of a cell in a DataGridView. There is no native
/// support for disabling a cell, hence the need for this method. The disabled state
/// means that the cell is read-only and grayed out.
/// </summary>
/// <param name="dc">Cell to enable/disable</param>
/// <param name="enabled">Whether the cell is enabled or disabled</param>
private void enableCell(DataGridViewCell dc, bool enabled) {
//toggle read-only state
dc.ReadOnly = !enabled;
if (enabled)
{
//restore cell style to the default value
dc.Style.BackColor = dc.OwningColumn.DefaultCellStyle.BackColor;
dc.Style.ForeColor = dc.OwningColumn.DefaultCellStyle.ForeColor;
}
else {
//gray out the cell
dc.Style.BackColor = Color.LightGray;
dc.Style.ForeColor = Color.DarkGray;
}
}
Upvotes: 47
Reputation: 103467
You can set a particular row or cell to be read-only, so the user cannot change the value. Is that what you mean?
dataGridView1.Rows[0].ReadOnly = true;
dataGridView1.Rows[1].Cells[2].ReadOnly = true;
Upvotes: 18