如何向DataGridView中的列添加按钮 [英] How to add a button to a column in the DataGridView

查看:95
本文介绍了如何向DataGridView中的列添加按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

文本出现但按钮从未出现.

The text appears but button never shows up.

推荐答案

假设你在 Windows 窗体中,你需要在你的 DataGridView 中添加一个 DataGridViewButtonColumn - 不是直接到 DataTable.

Assuming you are in Windows Forms, you need to add a DataGridViewButtonColumn to your DataGridView - Not directly to the DataTable.

这应该在您将 DataTable 绑定到 DataGridView 之后发生.

This should occur somewhere after you bind the DataTable to the DataGridView.

这样的事情应该可以工作:

Something like this should work:

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 事件才能对按钮执行任何操作.

Of course you will have to handle the CellClick event of the grid to do anything with the button.

在你的 DataGridView 初始化代码中添加这个

Add this somewhere in your DataGridView Initialization code

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.
    }
}

这篇关于如何向DataGridView中的列添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆