簡體   English   中英

如何將按鈕添加到 datagridview 單元格而不是整列

[英]How to add buttons to datagridview cells not entire column

如何將按鈕添加到行中的單元格而不是 datagridview 中的整個列?

我認為阿德里安的回答很接近。 嘗試這樣的事情。

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();
}

我最終做的是將一個 DataGridView 堆疊在另一個之上。 我關閉了邊框、網格線和滾動條。 然后創建動態按鈕列以僅與一行按鈕匹配主datagridview。 然后我使用 ColumnWidthChanged 事件處理程序一起調整兩個 DataGridViews 的大小。 無論如何,這是我現在的解決方法。

我認為如果在這里找到最好的答案: 隱藏 gridview 按鈕 您需要做的就是在需要按鈕的地方添加 DataGridViewButtonCell,在不需要的地方添加 DataGridViewTextBoxCell。 該列必須是 DataGridViewButton 類型。

在 SO 中看到這個類似的帖子,可能有幫助

將控制添加到 gridview

如果 Win Form,請查看此 MSDN 帖子

Windows Forms 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();
}

嘗試這樣的事情。

 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);

這會將按鈕添加到定義列索引處的每一行。 如果你想渲染條件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 以編程方式添加行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM