如何将按钮添加到数据网格视图单元格而不是整个列

本文关键字:单元格 视图 网格 按钮 添加 数据网 数据 | 更新日期: 2023-09-27 17:58:56

如何将按钮添加到数据网格视图中的行中的单元格,而不是整个列?

如何将按钮添加到数据网格视图单元格而不是整个列

我认为Adrian的回答很接近。试试这样的东西。

if ((string)table.Rows[0].Cells[0].Value == "I should be a button") {
   // you can add formatting or values to the button before assigning it here
   table.Rows[0].cells[0] = new DataGridViewButtonCell();
}

我认为最好的答案是:隐藏网格视图按钮。您所需要做的就是在需要按钮的位置添加DataGridViewButtonCell,在不需要按钮的地方添加DataGridView TextBoxCell。列必须是DataGridViewButton类型。

在SO中看到这篇类似的帖子,可能有助于

将控件添加到gridview

如果是Win Form,请查看此MSDN post

Windows窗体DataGridView控件中的列类型

或者这个代码项目帖子。。。尽管它给出了添加图像按钮的例子

DataGridView图像按钮单元格

@tmax在这种情况下,你可能会把你的按钮创建代码放在GridView_RowCreated事件中,就像下面的一样

void GridView_RowCreated(Object sender, GridViewRowEventArgs e)
  {   
     if(e.Row.RowType == DataControlRowType.Header)
      {   
           //Button creation code here        
      } 
  }
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    Button btn = new Button();
    //btn attributes
    dataGridView1.Rows[0].Cells[3].Value = new Button();
}

试试这样的东西。

我最终做的是将一个DataGridView堆叠在另一个之上。我关闭了边框、网格线和滚动条。然后创建动态按钮列,使主数据网格视图只与一行按钮相匹配。然后,我使用ColumnWidthChanged事件处理程序一起调整两个DataGridView的大小。无论如何,这是我目前的变通办法。

 DataGridViewButtonColumn dataGridViewButtonColumn = new DataGridViewButtonColumn();
        dataGridViewButtonColumn.Name = "Select";
        dataGridViewButtonColumn.HeaderText = "Select";
  
        dataGridViewButtonColumn.ReadOnly = false;
        dataGridView1.Columns.Add(dataGridViewButtonColumn);

将数据源分配给gridviewCTRL之后。您可以使用下面的代码通过按钮添加新列。

DataGridViewButtonColumn startbtn = new DataGridViewButtonColumn();
startbtn.Name = "Action";
startbtn.Text = "Start";
startbtn.UseColumnTextForButtonValue=true;
int columnIndex = 6;
gridviewCTRL.Columns.Insert(columnIndex, startbtn);

这将向define列索引处的每一行添加按钮。如果要渲染AccessibleObject条件,则可以执行类似于下面的操作。

foreach (DataGridViewRow rowdata in gridviewCTRL.Rows)
{
    // this is just an example in my case i am checking a previous column value
    if (rowdata.Cells[5].Value=="XYZ")
    {  
          rowdata.Cells[6] = new DataGridViewTextBoxCell();
    }
}

通过这种方式,您可以在Winforms c#中的GridView中动态呈现/显示控件。

上面的代码简单地用新的单元格更新单元格。我们不能从单元格中删除按钮,也不能删除整体,所以我们可以初始化一个新的单元格,它将覆盖按钮的可见性。

我不确定这是否有帮助,但您也可以考虑使用TableLayoutPanel。

请参阅:Winforms TableLayoutPanel以编程方式添加行