如何将一个按钮,在DataGridView中添加一列 [英] How to add a button to a column in the 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窗体中,您需要添加一个 DataGridViewButtonColumn
你的 DataGridView的
- 不直接将数据表
Assuming you are in Windows Forms, You need to add a DataGridViewButtonColumn
to your DataGridView
- Not directly to the DataTable
.
这应该某处你绑定后发生<$ 。C $ C>数据表到 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;
然后创建处理程序:
Then create the handler:
private void dataGridViewSoftware_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridViewSoftware.Columns["uninstall_button"].Index)
{
//Do Something with your button.
}
}
这篇关于如何将一个按钮,在DataGridView中添加一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!