簡體   English   中英

如何在DataGridView中顯示獨立按鈕?

[英]How can I show independent buttons in a DataGridView?

我有一個DataGridView帶有從數據庫中加載的元素。
問題是我想在某些行中顯示一個按鈕(某些元素需要此按鈕,而其他元素則不需要),而我不知道如何。
我現在唯一擁有的就是這段代碼,但每一行都顯示一個“刪除”按鈕。

DataGridViewButtonColumn btnDelete = new DataGridViewButtonColumn();
dataGridView.Columns.Add(btnDelete);
btnDelete.Text = "Delete";
btnDelete.UseColumnTextForButtonValue = true;

謝謝您的幫助!

您可以通過將DataGridViewButtonCells插入到想要按鈕的單元格中來實現。

例如:

var cell = new DataGridViewButtonCell();
cell.Value = "Button text"
cell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGrid.Rows[rowIndex].Cells[columnIndex] = cell;

該列不必是按鈕列,例如,它可以是文本框列。

或者,您也可以采用另一種方法,在按鈕列中輸入以下內容:

for (int i = 0; i < dataGrid.Rows.Count; i++)
    if (i % 2 == 1) // whatever the condition is
        dataGrid.Rows[i].Cells[COLUMN_WITH_BUTTONS] = new DataGridViewTextBoxCell();

您還可以創建一個自定義的datagrid列和單元格類型(從最接近您所需要的列的單元格繼承),它具有一個標志(添加)來控制單元格中顯示的內容。

您不需要立即為整個網格執行此操作-您可以隨時更改網格。 例如,您可以創建一個將單元格設置為適當類型的函數,然后在發生事件時(在事件處理程序中)將其調用。

暫無
暫無

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

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