LinkButton in a GridView to delete
We can delete a row in a GridView several ways. But I am here to explain how to use a LinkButton to delete a row. LinkButton is a fantastic control for raising a PostBack at the same time it is very flexible to style and format using style sheets and CSS.
DataBind the GridView
Note: As it is already explained in earlier articles several times, I am not going to explain again how to get the data and how to bind the data from database. So please refer to the Asp.net DataControls section or GridView walkthrough section for that matter.
I usually take the Northwind sample database for articles. So in this article I will be using the products table.
Use LinkButton inside a GridView
You can use the LinkButton inside a GridView with the help of TemplateField. Use the ItemTemplate in the TemplateField for displaying the LinkButton. To get the clicked row information in the code behind, LinkButton has two properties mainly to interact. That is CommandName and CommandArgument.
CommandName
CommandName can be used to define what the action the LinkButton is going to be performed. In our case it is going to perform Delete but wait don’t use delete as a CommandName. The reason behind is, the button field in the GridView is already using the delete name. So it will force the GridView to fire the GridView delete command. So you will not be getting the RowCommand event. So always be specific on actions and try to avoid the inbuilt action commands. Unless you are purposely raising the delete command please stay away from using the built-in action commands.
CommandArgument
Now we know how to use the CommandName property to specify the actions. Now it is time to pass the active data (in our case it is a primary key which is product id). The easiest way to pass the product id from markup to code behind on PostBack is using the command argument.
To bind the product id to the LinkButton using command argument, we can use the Databinder.Eval to get the product id for the respective row like the following
'<%# DataBinder.Eval(Container.DataItem, "ProductID")%>'>
Source Code
Mark up
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView runat="server" AutoGenerateColumns="false"
ID="GridView1">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDelete"
Text="X" CommandName="DELETE_PRODUCT"
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ProductID")%>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code behind
Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Private ReadOnly Property ConnectionString() As String
Get
Return "Server=.\SQLEXPRESS;Database=NorthWind;Trusted_Connection=True"
End Get
End Property
Private ReadOnly Property Connection() As SqlConnection
Get
Dim ConnectionToFetch As New SqlConnection(ConnectionString)
ConnectionToFetch.Open()
Return ConnectionToFetch
End Get
End Property
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Protected Sub GridView1_RowCommand(ByVal sender As Object, _
ByVal e As GridViewCommandEventArgs) Handles GridView1.RowCommand
If (e.CommandName = "DELETE_PRODUCT") Then
'Delete button is clicked
Dim ProductId = e.CommandArgument.ToString()
DeleteProduct(ProductId)
LoadGrid()
End If
End Sub
Private Sub LoadGrid()
GridView1.DataSource = GetData()
GridView1.DataBind()
End Sub
Public Function GetData() As DataTable
Dim SelectQry = "select * from Products"
Dim SampleSource As New DataSet
Try
Dim SampleDataAdapter As New SqlDataAdapter(SelectQry, ConnectionString)
SampleDataAdapter.Fill(SampleSource)
If (SampleSource.Tables.Count > 0) Then
Return SampleSource.Tables(0)
Else
Return Nothing
End If
Catch ex As Exception
Throw ex
End Try
Return Nothing
End Function
Private Sub DeleteProduct(ByVal ProductId As String)
Dim DelQry = "Delete from Products where ProductId=@ProductId"
Dim DelCommand As New SqlCommand(DelQry, Connection)
Dim ProductIdParameter = New SqlParameter("@ProductId", ProductId)
ProductIdParameter.Value = ProductId
DelCommand.Parameters.Add(ProductIdParameter)
DelCommand.ExecuteNonQuery()
End Sub
End Class