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

查看:239
本文介绍了如何在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 c中添加一个 DataGridViewButtonColumn code> - 不直接到 DataTable

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

这应该发生在绑定 DataTable 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天全站免登陆