繁体   English   中英

DataGridView 只读单元格

[英]DataGridView read only cells

我有一个包含大量数据的绑定 DataGridView。 问题是某些单元格必须是只读的,而且当用户在单元格之间使用 TAB 或 ENTER 导航时,应该绕过只读单元格。 加载后立即使某些特定单元格只读的最佳方法是什么?

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

在绑定数据之前,尝试将列而不是单个单元格设为只读:

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;

我使用以下代码遍历数据网格:

dataGridViewTest.DataSource = persons;

foreach (DataGridViewRow row in dataGridViewTest.Rows)
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        if (cell.Value.ToString() == "John")
        {
            cell.ReadOnly = true;
        }
    }
}

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

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

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;
}

一旦该列是只读的(请参阅 Rashmi 的响应),您就可以处理此事件...

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

        return;
    }

}

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

谢谢

你能不能不使用模板列而不是绑定列然后有一个字段的只读条件?

然后,您可以显示一个只读标签和一个可编辑文本框。 标签不会干扰您的标签索引。

<asp:TemplateColumn>
  <ItemTemplate>
<%
    if ( <%# Eval( "ReadOnlyFlag" ) %> )
    { 
%>
    <asp:Label Text="<%# Eval( "BoundColumn" ) %>" />
<%
    }
    else
    {
 %>
    <asp:Textbox Text="<%# Eval( "BoundColumn" ) %>" />
<%
    }
%>
    </ItemTemplate>
</asp:TemplateColumn>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM