This is pretty easy to do with a DataGridView . What you need to do:
Add a column of type DataGridViewButtonColumn
DataGridViewButtonColumn is a standard type of DataGridView column. It can be added through the constructor, but I usually prefer to use code (usually in the form constructor).
DataGridViewButtonColumn col = new DataGridViewButtonColumn(); col.UseColumnTextForButtonValue = True; col.Text = "ADD"; col.Name = "MyButton"; dataGridView1.Columns.Add(col);
Setting UseColumnTextForButtonValue true means that the Text property is applied to all buttons giving them the text of the "ADD" button. You can also use DataPropertyName to specify a column in the grid data source to provide button text, or you can even set the value of each cell directly.
Change buttons to text
After you have a column with buttons, you want to turn individual buttons into text. You do this by replacing the button type cell with one text type. You can do this in many places, but one of the best in the DataBindingComplete event handler is that this event fires after the grid is attached and ready to be displayed, but before it is colored.
Below I just take the line with index 1, but you can also check the properties of each Value line.
void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { dataGridView1.Rows[1].Cells["MyButton"] = new DataGridViewTextBoxCell(); }
Button Response
The last part of the problem responds to button presses. This is a bit awkward - you need to either use the CellClick event or the EditingControlShowing event for the entire grid.
Cellclick
private void DataGridView1_CellClick(object sender, System.Windows.FormsDataGridViewCellEventArgs e) { if (DataGridView1.Columns[e.ColumnIndex].Name == "MyButton") {
EditingControlShowing
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (e.Control is Button) { Button btn = e.Control as Button; btn.Click -= new EventHandler(btn_Click); btn.Click += new EventHandler(btn_Click); } } void btn_Click(object sender, EventArgs e) { int col = this.dataGridView1.CurrentCell.ColumnIndex; int row = this.dataGridView1.CurrentCell.RowIndex;
In your case, the editing control approach is probably best because it will not respond to clicking on buttons that have been replaced with text. Also, this method is more like how you react to any other button in the form.
David hall
source share