How do I add button in each row of column of already bound datagridview in Windows application?

时光毁灭记忆、已成空白 提交于 2021-02-08 04:09:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!