在DataGridView中添加按鈕可以通過以下步驟完成:
DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
dataGridView.Columns.Add(buttonColumn);
buttonColumn.HeaderText = "操作";
buttonColumn.Name = "buttonColumn";
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 = "按鈕文本";
}
}
dataGridView.CellClick += DataGridView_CellClick;
private void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView.Columns[e.ColumnIndex].Name == "buttonColumn" && e.RowIndex >= 0)
{
// 執行按鈕點擊操作
}
}
通過以上步驟,你可以在DataGridView中添加一個按鈕列,并為按鈕列的每個單元格設置按鈕文本。在單擊按鈕時,可以執行相應的操作。