问题
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.
回答1:
before binding to the datasource set :
grd.AutoGenerateColumns = false;
create yourself all DataGridView columns and bind them to the datasource:
DataGridViewTextBoxColumn dgvc = new DataGridViewTextBoxColumn();
dgvc.HeaderText = "column_header";
dgvc.DataPropertyName = "column_name";
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";
Add created columns to the DataGridView:
grd.Columns.Add(dgvc);
grd.Columns.Add(dgvbt);
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/en-us/library/system.windows.forms.datagridviewbuttoncolumn.aspx
来源:https://stackoverflow.com/questions/1410070/how-do-i-add-button-in-each-row-of-column-of-already-bound-datagridview-in-windo