-->

Thursday, October 31, 2013

How to Add Commands with Binding in DataGridView: Windows Forms

How to Add Commands with Binding in DataGridView: Windows Forms

After binding records with DataGridView, there may be some options to edit or to remove those records. To do these simple task we can provide either a button, which gets the selected record and perform operation, or we can provide the button with each particular record.

We will discuss here how to add a button with particular record with the following simple steps. Drag-n-drop a datagridview on the form and a task pop-up menu will automatically open, click on Add Columns link button to add a new column. It will show following Add Column window.

How to Add Commands with Binding in DataGridView: Windows Forms

By default Unbound column radio button have been checked, if not check it and use the following values in respective fields:
  • Type: DataGridViewButtonColumn
  • Header Text: Command (Changeable)
Sure the Visible check box is checked and click on Add button to add this column. Now you have successfully added a command button with empty text as shown in below image:

How to Add Commands with Binding in DataGridView: Windows Forms

To write text on the button generate Cell_Formatting event of dataGridview and set the value of first column as I do in the following c# code:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
dataGridView1.Rows[e.RowIndex].Cells[0].Value = "Remove";
}

When you run the project now, it will show “remove” on the button. To check if this code will works for multiple records or not, add some records in data gridview like How to add Records in Datagridview. Run the project now and it will show the Remove button with each record as shown in the following image:

How to Add Commands with Binding in DataGridView: Windows Forms

In the next article I will remove the particular record with this command button.

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved