【问题标题】:How display some cell without button and some with a button in datagridview如何在datagridview中显示一些没有按钮的单元格和一些有按钮的单元格
【发布时间】:2015-03-13 18:00:24
【问题描述】:

我有一个 DataGridView,我希望在我的网格中有一个列,其中包含一些显示按钮的单元格和一些不包含按钮的单元格。 为了解决这个问题,我添加了一个 DataGridViewButtonColumn 并编写了这个方法,我调用它来将行添加到我的列中:

 private void AttachNewRow(bool validRow)
 {
     DataGridViewRow newRow = GetNewRow();
     if (validRow)
     {
         newRow.Cells["Info"].Value = "Click me";
     }
     else
     {
         // Here I would like to hide the button in the cell
         newRow.Cells["Info"].Value = null;
     }
 }

问题是当我将单元格值设置为 null 时,我收到一个异常。 如何在没有按钮的情况下显示其中一些单元格? 谢谢

【问题讨论】:

    标签: c# datagridview datagridviewbuttoncolumn


    【解决方案1】:

    看起来GetNewRow() 返回了您所说的Row 已经插入DGV

    如果该函数知道“信息”Column 是否应包含Button,它可以传递它,也许在Tag 中:

    if (somecondiiotn) newRow.Columns["Info"].Tag = "Button";
    

    然后你可以写:

    private void AttachNewRow()
    {
        DataGridViewRow newRow = GetNewRow();
        if ( newRow.Cells["Info"].Tag == null || 
             newRow.Cells["Info"].Tag != "Button") return;
        //..
    

    如果调用AttachNewRow() 的代码具有所需的知识,它可以改为在参数中传递它:

    private void AttachNewRow(bool infoButton)
    

    如果知识稍后才可用,您仍然可以更改单个单元格。

    更新:

    由于您现在将条件传递给方法,因此您可以采取相应措施。

    我不知道为什么您的代码会出现异常 - 我不知道。但要真正隐藏Button,您应该将单元格更改为“正常”DataGridViewTextBoxCell

    else
    {
       DataGridViewCell cell = new DataGridViewTextBoxCell();
       newRow.Cells["Info"] = cell;
    

    【讨论】:

    • 您好 TaW,由于您的回复,我试图重写问题,但我意识到不清楚。现在明白我的意思了吗?非常感谢
    • 查看更新后的答案。你怎么崩溃了?在哪条线上?您是否更改了代码,以便信息列是一个按钮列开始?我假设您现在就这样做了,只需将无效行改回即可。如果它们有效,您可以以相同的方式将它们切换回 Button..
    • 异常出现在 newRow.Cells["Info"].Value = null;你的回答解决了我的问题,非常感谢
    • 奇怪,我可以这样做.. 但如果它按您的需要工作,一切都很好。顺便说一句:丹麦语插入ReadOnly = true;
    【解决方案2】:

    您可以在 RowAdded 事件处理程序中尝试类似的操作。这里假设第三列是按钮列:

    if (condition)
            {
    
                dataGridView1.Rows[e.RowIndex].Cells[2]  = new DataGridViewTextBoxCell();
                dataGridView1.Rows[e.RowIndex].Cells[2].ReadOnly = true;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 2016-02-12
      • 2021-05-15
      • 1970-01-01
      • 2022-12-30
      相关资源
      最近更新 更多