How to add Buttons in Data GridView?


Want to add buttons to the GridView control in Asp.net? Need to execute a set of statements when the user clicks on the button in the GridView? Learn how to add controls like button to the GridView control and write C# code for user activities performed like Clicking of Buttons in the GridView.

Adding Buttons in a GridView is a very simple procedure where developers have to put a few lines of codes in the Source code inside the GridView tag and capture the Click event of the button or Row Command event of GridView to execute the required block of code.

A GridView is a very powerful control which is used to display, insert and update data from data tables through the front end of an application. Controls like buttons, links, image buttons, checkboxes etc. can be added or inserted in an Asp.net GridView. After the addition of these controls the related events can be coded to perform a particular task as per the requirement of the application. Here we would learn how to add buttons in a Grid View through a sample code in C#.

We can add Buttons in a GridView in several ways. In the source code we can either add a button to the gridview by using <asp:ButtonField> tag or like in an earlier article about Adding Checkbox to a GridView control, we can use the <Template Field> tag.

In this article I would be covering the procedure to add buttons in the gridview :

  1. By using Template Field and capturing the On_Click event of the button to add the required C# code.

  2. By using Button Field and using the event OnRowCommand of the GridView to put the related C# code.


  3. Source Code for Adding Buttons in a GridView using Template Field


    Let's first start with learning how to insert a button in a GridView by making use of the Template Field. The code is as follows:

    <asp:GridView ID="gvw_emp" runat="server" AutoGenerateColumns="False">
    <Columns>
    <asp:BoundField DataField="emp_id_pk" HeaderText="Employee ID" />
    <asp:BoundField DataField="emp_fullname" HeaderText="Full Name" />
    <asp:BoundField DataField="emp_designation" HeaderText="Designation"/>

    <%-- Adding button to gridview --%>
    <asp:TemplateField HeaderText="Employee Profile" >
    <ItemTemplate>
    <asp:Button ID="Btn1" runat="server"
    Text="Show Profile" CommandArgument="Button1"
    OnClick="Btn1_Click" />
    </ItemTemplate>
    </asp:TemplateField>

    </Columns>
    </asp:GridView>


    In the above code we have specified the event OnClick and also declared that on the event of click of the control the function Btn1_Click would be called. After you have added the above code to the Asp.Net source code for the Grid View the control will look something like this:
    Databounded GridView

    C# code for retrieving row index on Click of Buttons in Gridview


    We mostly use controls like buttons inside the GridView for some specific task that we want to perform on the click of these buttons like deleting that particular row or editing data from some specific cells etc. In this sample code I have used the buttons in the gridview to show the profile of that particular employee.

    Here I have used the Click event of the button in the GridView to put the code for displaying the profiles of the corresponding employees. To display the details I would be using the Detail View control.

    We would first connect the GridView to the data source programmatically using C# as shown in the following screenshot:
    GridView data binding

    After data binding, the GridView will get populated with the data present in the corresponding data table.

    In order to execute the required task we would need to capture the click event of the button in the gridview. The code we need to retrieve/get the row index in order to find the index of the row for which the even OnClick occurred is given below. Thus when the button in the GridView will be clicked the following code will get executed:

    protected void Btn1_Click(object sender, EventArgs e)
    {
    GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
    int index = gvRow.RowIndex;

    //Fetches the employee id corresponding to the row index
    string emp_id = gvw_emp.Rows[index].Cells[0].Text;

    pnl_profile.Visible = true;

    command.CommandText ="select * from EmpDetails,EmpProfile
    where EmpDetails.emp_id_pk = EmpProfile.emp_id_pk
    and EmpProfile.emp_id_pk = '" + emp_id + "'";

    //Binding the Detail View
    adapter.Fill(dtset, "rowtable");
    dv_profile.DataSource = dtset.Tables["rowtable"];
    dv_profile.DataBind();
    .
    .
    .
    }
    }


    In the above code the sender which is a button control will have to be type casted in order to refer the Gridview Row object. Here the sender is the button control and hence its parent will be the cell which contains the control and again its parent will be the row which contains that cell. Thus we will be able to get a reference to the particular row whose button was clicked. The RowIndex property would then provide the index of the associated row.

    On execution we would get the following output where on the click of the "Show Profile" button we would be able to retrieve the profile of that particular employee id.

    Adding Buttons in Grid View Control

    Source Code for Adding Buttons in a GridView using Button Field


    The other method of inserting button in a GridView by using the Button Field is somewhat simpler. Here we would use the buttonfield tag as in the code below:


    <Columns>
    <asp:BoundField DataField="emp_id_pk" HeaderText="Employee ID" />
    <asp:BoundField DataField="emp_fullname" HeaderText="Full Name" />
    <asp:BoundField DataField="emp_designation" HeaderText="Designation" />
    <asp:ButtonField ButtonType="Button"
    CommandName="ShowProfile" Text="Show Profile"
    CausesValidation="false" />
    </Columns>
    </asp:GridView>


    Here we will have to use the RowCommand even of the gridview control. When a button would be clicked the RowCommand event will be fired. We will have to specify in the source code which event/function we would want to execute when the firing of OnRowcommand event.

    C# code for getting the row index using the OnRowCommand event


    Here when the RowCommand event of GridView will be fired on the click of the button a user function will be called where the code for execution is specified. The code for this sample program is as follows:

    protected void gvw_emp_OnRowCommand(object sender,
    System.Web.UI.WebControls.GridViewCommandEventArgs e)
    {

    string currentCommand = e.CommandName;
    int index = Int32.Parse(e.CommandArgument.ToString());

    //The rest of the code follows......

    }


    In this code we have used the property "CommandArgument" which contains the row index of the rows in the GridView.


More articles: Buttons in GridView

Comments

Guest Author: JH08 Feb 2013

How to add button inside a cell?

Author: Phagu Mahato23 Dec 2013 Member Level: Gold   Points : 6

You can manage easily in the CellContentClickEvent the column and row which is clicked and then do the job.

If you want to manage access right (like allowing someone to editing and someone else to not editing) you can play with show/hide of this column.You can use this sample code snippet for add button in cell


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

DataSet ds = new DataSet();
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.TableName = "MaterialsTransactions";
for (int i = 0; i < 5; i++)
{
dt.Columns.Add(i.ToString());
}

dt.Rows.Add("1", "2", "3", "4", "5");
dt.Rows.Add("a", "b", "c", "d", "e");

ds.Tables.Add(dt);
MaterialDG.DataSource = ds;
MaterialDG.DataMember = "MaterialsTransactions";
MaterialDG.RightToLeft = RightToLeft.Yes;
MaterialDG.AllowUserToAddRows = false;
MaterialDG.Columns[0].HeaderCell.Value = "Employee Record";
MaterialDG.Columns[1].HeaderText = "Name";
MaterialDG.Columns[2].HeaderText = "Desig";
MaterialDG.Columns[3].HeaderText = "Payment";
MaterialDG.Columns[4].HeaderText = "Detail";



DataGridViewButtonColumn buttons = new DataGridViewButtonColumn();
buttons.HeaderText = "Submit";
buttons.Text = "Reset";
buttons.UseColumnTextForButtonValue = true;
buttons.AutoSizeMode =
DataGridViewAutoSizeColumnMode.AllCells;
buttons.FlatStyle = FlatStyle.Standard;
buttons.CellTemplate.Style.BackColor = Color.Honeydew;
buttons.DisplayIndex = 5;
MaterialDG.Columns.Add(buttons);

}
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: