0

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

有没有办法做到这一点?

4

1 回答 1

3

您可以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)

...在您的课程中提供此功能:

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# 标签。

于 2021-10-15T16:32:53.097 回答