如何向DataGridView中的列添加按钮

时间:2014-01-17 17:18:28

标签: c# winforms datagridview datatable datarow

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Software Title", typeof(string)));
dt.Columns.Add(new DataColumn("Version", typeof(string)));
dt.Columns.Add(new DataColumn("Uninstall", typeof(System.Windows.Forms.Button)));

DataRow dr = dt.NewRow();
dr[0] = "App";
dr[1] = "1.0";
Button uninstall = new Button();
uninstall.Text = "Uninstall";

dr[2] = uninstall;

dt.Rows.Add(dr);

dataGridViewSoftware.DataSource = dt;

出现文本但按钮从不显示。

2 个答案:

答案 0 :(得分:31)

假设您使用的是Windows窗体,则需要向DataGridViewButtonColumn添加DataGridView - 不要直接添加到DataTable

DataTable绑定到DataGridView

后,应该会发生这种情况

这样的事情应该有效:

DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "uninstall_column";
uninstallButtonColumn.Text = "Uninstall";
int columnIndex = 2;
if (dataGridViewSoftware.Columns["uninstall_column"] == null)
{
    dataGridViewSoftware.Columns.Insert(columnIndex, uninstallButtonColumn);
}

当然,您必须处理网格的CellClick事件才能对按钮执行任何操作。

在DataGridView初始化代码

中添加它
dataGridViewSoftware.CellClick += dataGridViewSoftware_CellClick;

然后创建处理程序:

private void dataGridViewSoftware_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == dataGridViewSoftware.Columns["uninstall_column"].Index)
    {
        //Do something with your button.
    }
}

答案 1 :(得分:8)

简单。

DataGridViewButtonColumn button = new DataGridViewButtonColumn();
{
    button.Name = "button";
    button.HeaderText = "Button";
    button.Text = "Button";
    button.UseColumnTextForButtonValue = true; //dont forget this line
    this.dataGridView1.Columns.Add(button);
}