How to add a button column in a DataGridView?

To add a button column in the DataGridView, you can achieve it by following these steps:

  1. Setting the AllowUserToAddRows property of the DataGridView control to false ensures that only manually added rows will be displayed in the control.
  2. You can add a DataGridViewButtonColumn column to the Columns collection of a DataGridView control by using the following code:
DataGridViewButtonColumn btnColumn = new DataGridViewButtonColumn();
btnColumn.HeaderText = "操作"; // 设置列标题
btnColumn.Text = "按钮名称"; // 设置按钮显示的文字
btnColumn.UseColumnTextForButtonValue = true; // 使用列中的文本作为按钮的显示文字

dataGridView1.Columns.Add(btnColumn); // 将按钮列添加到DataGridView中
  1. If you want to trigger an event when a button is clicked, you can achieve this by using the DataGridView’s CellContentClick event. In this event, you can determine the clicked column and row, and then perform the corresponding operation. For example:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == dataGridView1.Columns["操作"].Index && e.RowIndex >= 0)
    {
        // 执行按钮点击时的操作
        MessageBox.Show("点击了按钮");
    }
}

By following the above steps, you can add a button column in a DataGridView and perform the corresponding operation when the button is clicked.

 

 

More tutorials

How to display data in a DataGridView table?(Opens in a new browser tab)

The similarities and differences of ListBox and DataGridView(Opens in a new browser tab)

A tutorial on the Python Pandas module.(Opens in a new browser tab)

get pandas DataFrame from an API endpoint that lacks order?(Opens in a new browser tab)

How to create a button control in WinForms?(Opens in a new browser tab)

 

 

Leave a Reply 0

Your email address will not be published. Required fields are marked *