如何使单元格仅在填充后才可读?数据网格视图 C#

How can I make a cell to read only when it has been filled? DataGridView C#

我想在具有多列的 DataGridView 上显示 table,所有列都是只读的,只有一列。 这一列需要具有由用户填充的容量,但我想让已经有内容的单元格只读,而不是所有列,这样用户仍然可以填充列上的剩余单元格(已填写者除外)

有办法实现吗?

您可以像这样简单地设置 CellEndEdit 事件:

private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCell cell =        this.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex);
    cell.ReadOnly = true;
}

VB.NET:

Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
    Dim cell As DataGridViewCell = Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
    cell.ReadOnly = True
End Sub

如果你在DataGridView开头有数据,你可以在加载数据后设置访问权限,如下所示:

SetAccess(this.DataGridView1);

VB.NET:

Call SetAccess(Me.DataGridView1)

...在您的 class:

中提供此功能
private void SetAccess(DataGridView dgw)
{
    for (var ir = 0; ir <= dgw.Rows.Count - 1; ir++)
    {
        for (var ic = 0; ic <= dgw.Columns.Count - 1; ic++)
        {
            DataGridViewCell cell = this.DataGridView1.Rows(ir).Cells(ic);
            if (!IsNothing(cell.Value) && cell.Value.ToString.Length > 0)
                cell.ReadOnly = true;
        }
    }
}

VB.NET:

Private Sub SetAccess(dgw As DataGridView)
    For ir = 0 To dgw.Rows.Count - 1
        For ic = 0 To dgw.Columns.Count - 1
            Dim cell As DataGridViewCell = Me.DataGridView1.Rows(ir).Cells(ic)
            If Not IsNothing(cell.Value) AndAlso cell.Value.ToString.Length > 0 Then
                cell.ReadOnly = True
            End If
        Next
    Next
End Sub

经过测试,一切都很好。

显然你可以玩代码,即通过修改列循环的范围来排除最后一列:

For ic = 0 To dgw.Columns.Count - 2

VB.NET(相同):

For ic = 0 To dgw.Columns.Count - 2

抱歉,第一次回复时漏掉了 c# 标签。