溫馨提示×

c#怎么在datagridview中加按鈕

小億
1228
2023-08-07 20:40:34
欄目: 編程語言

在DataGridView中添加按鈕可以通過以下步驟完成:

  1. 將DataGridView控件的列類型設置為DataGridViewButtonColumn??梢酝ㄟ^以下代碼創建一個按鈕列:
DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
dataGridView.Columns.Add(buttonColumn);
  1. 可以為按鈕列設置標題和名稱:
buttonColumn.HeaderText = "操作";
buttonColumn.Name = "buttonColumn";
  1. 為DataGridView的CellFormatting事件添加一個事件處理程序。在處理程序中,可以為按鈕列的每個單元格設置按鈕文本:
dataGridView.CellFormatting += DataGridView_CellFormatting;
private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView.Columns[e.ColumnIndex].Name == "buttonColumn" && e.RowIndex >= 0)
{
DataGridViewButtonCell buttonCell = (DataGridViewButtonCell)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
buttonCell.Value = "按鈕文本";
}
}
  1. 可以為DataGridView的CellClick事件添加一個事件處理程序。在處理程序中,可以根據需要執行與按鈕相關的操作:
dataGridView.CellClick += DataGridView_CellClick;
private void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView.Columns[e.ColumnIndex].Name == "buttonColumn" && e.RowIndex >= 0)
{
// 執行按鈕點擊操作
}
}

通過以上步驟,你可以在DataGridView中添加一個按鈕列,并為按鈕列的每個單元格設置按鈕文本。在單擊按鈕時,可以執行相應的操作。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女