我想在 DataGridView 上顯示一個包含多列的表,所有列都只讀,但只有一個。這一列需要有用戶填充的容量,但我想讓已經有內容的單元格成為只讀,而不是所有的列,所以用戶仍然有填充列上剩余單元格的容量(已經填好的除外)
有沒有辦法實作這一目標?
uj5u.com熱心網友回復:
您可以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# 標簽。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/318258.html
標籤:C# winforms 数据网格视图 数据网格视图列 数据网格视图行
