c#怎么在datagridview中加按钮

1108
2023/7/10 20:40:34
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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中添加一个按钮列,并为按钮列的每个单元格设置按钮文本。在单击按钮时,可以执行相应的操作。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c#中arraylist怎么输出所有对象