【问题标题】:Can't control readonly property in a datagridview无法控制 datagridview 中的只读属性
【发布时间】:2020-05-03 19:40:16
【问题描述】:

我在 C# 应用程序中使用 datagridview。而且我需要只有一个特定的列是可编辑的,而不是整个列。最后一行必须是只读的。

我在设计时将 datagridview 只读属性设置为 false。然后我使用代码序列将所有其他列变为只读:

dataGridView1.Columns["Col1"].ReadOnly = true; dataGridView1.Columns["Col2"].ReadOnly = true; dataGridView1.Columns["Col3"].ReadOnly = true; dataGridView1.Columns["Col4"].ReadOnly = true;

datagridview 有 5 列。此时,只有 Col5 是可编辑的。但是我需要最后一行是只读的,所以我尝试了:

dataGridView1.Rows[dataGridView1.Rows.Count - 1].ReadOnly = true;

那没用,整个 Col5 仍然可以编辑。所以我尝试了:

dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Col5"].ReadOnly = true;

那也没有用。整个 Col5 仍然可以编辑。

我该如何解决?

【问题讨论】:

    标签: c# datagridview readonly


    【解决方案1】:

    方法一:

    您可以在数据绑定完成后更改行(或单元格)的只读状态:

    dataGridView1.DataBindingComplete += dataGridView1_DataBindingComplete;
    

    还有,

    void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        dataGridView1.Rows[dataGridView1.Rows.Count - 1].ReadOnly = true;
    }
    

    方法二:

    如果行是最后一行,您可以取消对任何单元格的编辑:

    dataGridView1.CellBeginEdit += dataGridView1_CellBeginEdit;
    

    和;

    void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        e.Cancel = e.RowIndex == dataGridView1.Rows.Count - 1;
    }
    

    【讨论】:

      【解决方案2】:

      尝试将设计中的datagridview.readonly属性设置为true。最后一列只读错误。并且在最后一行之后是只读的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 2015-11-14
        • 2019-05-08
        • 1970-01-01
        相关资源
        最近更新 更多