我希望在DataGridView上显示一个包含多个列的表,所有列都只读,只有一列。这一列需要具有由用户填充的容量,但我希望将已有内容的单元格设置为ReadOnly,而不是所有列,这样用户仍有能力填充列上的其余单元格(已填充的单元格除外)
有没有办法做到这一点?
发布于 2021-10-15 16:32:53
您可以像这样简单地设置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)在你的类中...providing这个函数:
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 - 2VB.NET (相同):
For ic = 0 To dgw.Columns.Count - 2抱歉,第一次回复时错过了c#标签。
https://stackoverflow.com/questions/69585281
复制相似问题