To add a button for each record in the GridView and perform some custom operation on click of this
button, we can follow this approach.
GridView control is a powerful data grid control that allows us to display the data in tabular format with facilities for sorting and pagination. It also allows us to manipulate the data.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="FireRowCommand" DataKeyNames="AutoId">
<asp:TemplateField HeaderText="Mark as Deleted">
<asp:LinkButton ID="btnDeleted" runat="server" CommandArgument='<%# Eval("AutoId") %>'
CommandName="MarkAsDeleted" Text="Mark As Deleted" />
<asp:TemplateField HeaderText="Mark as Archived">
<asp:LinkButton ID="btnArchived" runat="server" CommandArgument='<%# Eval("AutoId") %>'
CommandName="MarkAsArchived" Text="Mark as Archived" />
In the above code snippet, we have a GridView where we have kept two
TemplateField with LinkButtons. The first button CommandName is “
MarkAsDeleted” and the second button CommandName is “
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
private void GetData()
DataTable table = new DataTable();
// get the connection
using (SqlConnection conn = new SqlConnection(_connStr))
// write the sql statement to execute
string sql = "SELECT AutoId, FirstName, LastName, Age, Active FROM PersonalDetail ORDER By AutoId";
// instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
// get the adapter object and attach the command object to it
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
// fire Fill method to fetch the data and fill into DataTable
// specify the data source for the GridView
GridView1.DataSource = table;
// bind the data now
protected void FireRowCommand(object sender, GridViewCommandEventArgs e)
string command = e.CommandName;
string autoId = e.CommandArgument.ToString();
Response.Write("<b>Mark As Deleted for " + autoId + " </b> button clicked");
Response.Write("<b>Mark As Archived for " + autoId + " </b> button clicked");
When these "MarkAsArchived",“MarkAsDeleted” buttons are clicked the
OnRowCommand event fires that execute the
FireRowCommand sever side method. In this method, we have retrieved the CommandName and CommandArguments that we had set for buttons in the GridView. The CommandName differs from button to button and based on its value we have written text under the switch statement.
Note: The same can be achived using normal button as well instead of LinkButton.
Thanks for reading, hope you liked it.
Keep reading my forth coming articles. To read my series of articles on ASP.NET, click here