In a dynamic ASP.NET Gridview Delete row example

During we display data in a Gridview in many places Customer wants to implement checkbox in the grid for Select all & individual rows. Using this feature user can edit or delete records. Expected behavior is like user can select the rows which one he/she want to edit or delete. For edit purpose only one row need to select. While for delete multiple rows can be OK. During delete we need to ask confirmation. After confirmation we can go for delete records. The same I implemented in my App. Sharing you the code from there. Hope it will help you to implement your own.

ASP.NET Gridview

<asp:GridView DataKeyNames="VisitorTrackingID" CssClass="bodytext" AutoGenerateColumns="false" PageSize="18"
AllowPaging="True" AllowSorting="True" ID="grdVisitorTracking" runat="server"
Width="100%" CellPadding="2" BackColor="White" BorderColor="#CCCCCC"
BorderStyle="None" BorderWidth="1px">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input type="checkbox" style="width: 20px;" id="chkAll" onclick="javascript:checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<input type="checkbox" style="width: 20px;" id="chkSelect" runat="server" name="chkSelect" />
</ItemTemplate>
<HeaderStyle Width="25px"/>
</asp:TemplateField>
<asp:BoundField ItemStyle-CssClass="bodytext" HeaderStyle-HorizontalAlign="Left"
DataField="TrackingID" HeaderText="Tracking ID" SortExpression="TrackingID">
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:BoundField>
<asp:BoundField ItemStyle-CssClass="bodytext" HeaderStyle-HorizontalAlign="Left"
DataField="TrackingCompany" HeaderText="Company" SortExpression="TrackingCompany">
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:BoundField>

<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Weblink" SortExpression="TrackingUrl">
<ItemTemplate>
<a href='<%# Container.DataItem("TrackingUrl") %>' target="_blank" style="cursor: hand;">
<%# Container.DataItem("TrackingUrl") %></a>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:TemplateField>

<asp:TemplateField ItemStyle-CssClass="bodytext" HeaderStyle-HorizontalAlign="Left" HeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="hypEdit" runat="server" ImageUrl="../Images/grdEdit.png"></asp:HyperLink>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
<ItemStyle CssClass="bodytext" HorizontalAlign="Left"></ItemStyle>
</asp:TemplateField>
</Columns>
<RowStyle Height="20px" ForeColor="#000066" />
<FooterStyle BackColor="White" ForeColor="#000066" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#005b90" Font-Bold="True" ForeColor="White" />
<%--<AlternatingRowStyle BackColor="#E1F0FF" />--%>
</asp:GridView>

To implement delete functionality depending upon those rows we selected, here I added checkbox in the TemplateField of my Grid. For Select All I added a checkbox in HeaderTemplate & for rows I added another checkbox (HTML Control) in ItemTemplate. To make Select All operate on its onClick event I am calling a JavaScript function checkAll(this).

CheckAll() Function

function checkAll(obj)
{
if(obj.checked) markAllState = true;
else markAllState = false;
frm = document.forms[0];
for(i=0;i< frm.elements.length;i++)
{
e = frm.elements[i];
//GridView2$ctl01$check" type="checkbox" id="GridView2_ctl01_check
if (e.type == 'checkbox' && e.name != 'GridView2$ctl01$check')
{
temp='e.checked = '+markAllState;
eval(temp);
}
}
}

This function is responsible to Check all rows in the grid. The logic I implemented here is first I am getting all the checkbox from the form. Then to identify grid related checkbox I am doing a conditional checking if (e.type == ‘checkbox’ && e.name != ‘GridView2$ctl01$check’).

Once rows are selected to proceed ahead delete operation we need to show a confirmation to the user. To handle this I implemented the below JavaScript function.

Delete User Confirmation Function

function deluser()
{
var j= 0;
frm = document.forms[0];
for(i=0;i< frm.elements.length;i++)
{
e = frm.elements[i];

if (e.type == 'checkbox')
{
if(e.checked==true)
j=j+1;
}
}
//if(j>1 || j<1)
if(j<1)
{
alert("Please select a Visitor Tracking to Delete.")
return false;
}
//return true;
var con = confirm("Are you sure, You want to delete this Visitor Tracking.");
if(con) return true;
else return false;
}

This function checks state of the Check-boxes. If checkbox is checked it means user selected that row for delete. To get the confirmation from user showing a confirmation window with message “Are you sure, You want to delete this Visitor Tracking.”.

This is all about front-end. After user confirmation we need to fire delete query from code behind. Look at the Code below.

Code-Behind Delete Query

Protected Sub btnDel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDel.Click
Dim i As Integer
For i = 0 To grdVisitorTracking.Rows.Count - 1
Dim row As GridViewRow = grdVisitorTracking.Rows(i)
Dim ischecked As Boolean = (CObj(row).FindControl("chkSelect")).Checked
If (ischecked) Then
aDel.Add(grdVisitorTracking.DataKeys.Item(i).Value)
End If
Next
If Not aDel.Count <> 0 Then
'Do Nothing
Else
'Dim confirm = MsgBox("Are you sure you want to delete this item", MsgBoxStyle.OkCancel)
'If confirm = 1 Then
For i = 0 To aDel.Count - 1

Dim sDelStr As String = "DELETE FROM VisitorsTracking WHERE VisitorTrackingID=" & aDel(i)
Dim oDelComm As New SqlCommand(sDelStr, sqlConn)
sqlConn.Open()
oDelComm.ExecuteNonQuery()
sqlConn.Close()

grdVisitorTracking.DataBind()
Next
End If

Response.Redirect("../ADMIN/EditVisitorTracking.aspx")
End Sub

Finally for delete operation in Code-behind I am detecting chkSelect state. If it returns true I am storing its value to an array “aDel”. In next phase checking the count of aDel if it is greater then zero then executing SQL Delete command against that particular record id.