I have a binded DataGridView that contains a large amount of data. The problem is that some cells has to be ReadOnly and also when the user navigates with TAB or ENTER betwe
You can do this using the BeginningEdit
event to check if the check if the cell meets a condition and cancel the operation if not:
In the example below, if the cell already contains a value it will cancel the operation, deeming it as read only.
xaml
:
<DataGrid BeginningEdit="DataGrid_BeginningEdit" ItemsSource="{Binding Example, Mode=TwoWay}"/>
c#
:
private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
string content = (e.EditingEventArgs.Source as TextBlock).Text;
if (!(String.IsNullOrEmpty(content)))
e.Cancel = true;
}
Try to make the column rather than individual cells readonly before binding the data:
this.dgrid.Columns["colName"].ReadOnly = true;
If you need to do for individual cells within the column, then you will have to loop and set them like this:
this.dgridvwMain.Rows[index].Cells["colName"].ReadOnly = true;
You can use CellBeginEdit event and set e.Cancel = True when you need disable the cell.
Private Sub DataGridView_CellBeginEdit(sender As System.Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridViewMsg.CellBeginEdit
If DataGridViewMsg.Rows(e.RowIndex).Cells("disable").Value = "Y" Then
e.Cancel = True
End If
End Sub
Once the column is read only (see Rashmi's response) you can handle this event...
private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Tab)
{
Boolean readOnly = (sender as DataGridView).SelectedCells[0].ReadOnly;
return;
}
}
Which will get the next cell's read only property.
Thanks
this.dataGridViewEmpList.EditMode = DataGridViewEditMode.EditProgrammatically;
There's a very nice sample here:
http://blogs.msdn.com/netcfteam/archive/2006/04/25/583542.aspx
You just need to override Paint()
, I've used this on compact framework to change the backcolor depending on the cell contents so on the same note you shouldn't have any problem to set them read only.