DataGridView只读单元格

我有一个包含大量数据的绑定DataGridView。 问题是某些单元格必须是ReadOnly,当用户在单元格之间使用TAB或ENTER导航时,应绕过ReadOnly单元格。 在装载后,制作某些特定细胞的最佳方法是什么?

在设置DataSource之后循环遍历单元并不是一个好主意,考虑到网格有大量数据。 此外,在CellEnter上创建单元格ReadOnly不起作用,因为当使用TAB键导航时,我必须已经知道下一个单元格是否为ReadOnly。

在绑定数据之前,尝试使用列而不是单个单元格:

this.dgrid.Columns["colName"].ReadOnly = true; 

如果您需要对列中的单个单元格执行操作,则必须循环并将其设置为:

 this.dgridvwMain.Rows[index].Cells["colName"].ReadOnly = true; 

您可以使用CellBeginEdit事件,并在需要禁用单元格时设置e.Cancel = True。

 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 

我没试过这个。

但是,您可以在RowEnter事件上将单元格的readonly属性设置为true(根据Rashmi)?

我猜RowEnter事件应该从你从一行移动到另一行时触发(或者当你从单元格A1变为B3时它应该触发)。

这些帮助有用?

 this.dataGridViewEmpList.EditMode = DataGridViewEditMode.EditProgrammatically; 

一旦该列只读(参见Rashmi的回复),您就可以处理此事件……

 private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Tab) { Boolean readOnly = (sender as DataGridView).SelectedCells[0].ReadOnly; return; } } 

这将获得下一个单元格的只读属性。

谢谢

您可以使用BeginningEdit事件来检查是否检查单元是否满足条件,如果不满足则取消操作:

在下面的示例中,如果单元格已包含值,它将取消操作,将其视为只读。

xaml

  

c#

 private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e) { string content = (e.EditingEventArgs.Source as TextBlock).Text; if (!(String.IsNullOrEmpty(content))) e.Cancel = true; } 

您是否可以使用模板列而不是绑定列,然后具有该字段的只读的条件?

然后,您可以为readonly提供标签,为可编辑提供文本框。 标签不会干扰您的标签索引。

   <% if ( <%# Eval( "ReadOnlyFlag" ) %> ) { %> " /> <% } else { %> " /> <% } %>   

这里有一个非常好的样本:
http://blogs.msdn.com/netcfteam/archive/2006/04/25/583542.aspx

你只需要覆盖Paint() ,我已经在紧凑的框架上使用它来根据单元格内容更改背景颜色,所以在同一个注释上你应该没有任何问题将它们设置为只读。