如何在Windows应用程序中已绑定的datagridview的每一行中添加按钮? [英] How do I add button in each row of column of already bound datagridview in Windows application?
问题描述
我想向已绑定的datagridview的列的每一行添加一个按钮,并向其添加一个事件(在VS 2005中,在Windows应用程序中).
I want to add a button to each row of a column of an already bounded datagridview, and add an event to it (in VS 2005, Windows application).
我进行了很多搜索,但是找不到有效的解决方案.
I have searched a lot but was unable to find a working solution.
推荐答案
在绑定到数据源集之前:
before binding to the datasource set :
grd.AutoGenerateColumns = false;
创建所有DataGridView列并将其绑定到数据源:
create yourself all DataGridView columns and bind them to the datasource:
DataGridViewTextBoxColumn dgvc = new DataGridViewTextBoxColumn();
dgvc.HeaderText = "column_header";
dgvc.DataPropertyName = "column_name";
创建一个DataGridViewButtonColumn.
create a DataGridViewButtonColumn.
DataGridViewButtonColumn dgvbt = new DataGridViewButtonColumn();
如果不希望此列绑定,请在所有按钮上设置标题文本和相同的文本:
If you want this column not bound, set header text, the same text on all buttons:
dgvbt.HeaderText = "OK?";
dgvbt.Text = "ok"; // works also when bound
dgvbt.UseColumnTextForButtonValue = true; //
如果您希望列也受到限制,并且每个按钮都具有基础单元格的文本,则将其绑定:
If you want your column to be also bounded and each button have the text of underlying cell, bind it:
dgvbt.DataPropertyName = "column_bt";
将创建的列添加到DataGridView:
Add created columns to the DataGridView:
grd.Columns.Add(dgvc);
grd.Columns.Add(dgvbt);
处理DataGridView的CellClick事件:
handle the CellClick event of the DataGridView:
grd.CellClick += new DataGridViewCellEventHandler(grd_CellClick);
void grd_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex == index_of_button_column)
{
MessageBox.Show(this, e.RowIndex.ToString() + " Clicked!");
//...
}
}
有关更多信息,请参见:
for more, see:
http://msdn.microsoft.com/zh-cn/library/system.windows.forms.datagridviewbuttoncolumn.aspx
这篇关于如何在Windows应用程序中已绑定的datagridview的每一行中添加按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!