【问题标题】:How to set the ReadOnly of entire row in DataGridView based on condition?如何根据条件在DataGridView中设置整行的ReadOnly?
【发布时间】:2021-01-12 14:39:52
【问题描述】:

当我在 DataGridView 中循环遍历每一行时,不确定为什么设置行的 ReadOnly 属性不起作用(我仍然可以编辑所有行):

foreach (DataGridViewRow row in dataGridEthnicityData.Rows)
{
    string EthnicityProfilingCompanyName = row.Cells["EthnicityProfilingCompanyName"].Value.ToString();
    string EthnicityProfilingCompanyID = row.Cells["EthnicityProfilingCompanyID"].Value.ToString();

    if (EthnicityProfilingCompanyName != ProfilingEntityName && EthnicityProfilingCompanyID != ProfilingEntityID)
        row.ReadOnly = true;
    else row.ReadOnly = false;
}

如果有人能指出我正确的方向,不胜感激。我必须改变循环方式吗?我正在考虑使用带计数器的循环,以便将其用作行索引。

谢谢。

【问题讨论】:

  • 它不起作用怎么办?您点击了row.ReadOnly = true 行,但之后您仍然可以更改该行吗?你确定你没有落入else吗?
  • @BrootsWaymb 我仍然可以编辑我设置为 row.ReadOnly = true 的行。我调试并确保它通过了第一个 If 条件。
  • @KateB 对于此类问题,您应该分享minimal reproducible example,我们无法判断标准或代码的其他相关部分可能有什么问题。但在这里,我尝试用干净的最小代码分享答案。
  • @RezaAghaei 我很抱歉,发现该行被禁用,除了数据网格中的组合框和按钮。我的数据网格绑定到数据表,并且组合框也绑定了。
  • 正如答案中已经提到的,将您的 foreach 循环移动到 DataBindingComple 事件或作为更好的选择使用 CellBeginEdit 而不使用 foreach 循环。虽然 ComboBos 样式类似于下拉菜单,但它是只读的,并且无法编辑单元格。

标签: c# .net winforms datagridview


【解决方案1】:

如果要在循环中设置行的只读属性,则应确保在数据绑定完成并且行存在于 DataGridView 中之后运行代码。一个很好的事件是DataBindingComplete

但更好的选择(而不是在行上循环)是处理CellBeginEdit,这是一个可取消的事件,允许您检查单元格或行上的条件并决定允许或拒绝编辑。

示例 - 使用 CellBeginEdit 有条件地将 Row 设为只读

class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    var list = new List<Item>() {
        new Item(){ Id = 1, Name ="One"},
        new Item(){ Id = 2, Name ="Tow"},
    };
    var dg = new DataGridView();
    dg.Dock = DockStyle.Fill;
    dg.DataSource = list;
    dg.CellBeginEdit += (object obj, DataGridViewCellCancelEventArgs args) =>
    {
        var row = ((DataGridView)obj).Rows[args.RowIndex];
        if ((int)row.Cells[0].Value == 1)
            args.Cancel = true;
    };
    this.Controls.Add(dg);
}

以上代码禁止编辑第一行,但允许编辑第二行。

【讨论】:

  • 如果您能够查看并验证答案,那就太好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多