Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to get and delete multiple GridView rows in ASP.NET

Author: Alanna Kremer
Download Source Code : 1313_GetMutipleGridViewRows.zip

This article will explain how to get multiple selected rows in GridView and how to delete these rows from database.

 

GridView Control provides the facility to select or delete only one row at a time. However if you want to select multiple rows and want to delete these rows at the same time, you can add Checkbox to GridView. CheckBox control in GridView will allow you to check multiple items at the same time and you can use selected rows according your requirement.

 

  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual C# or Visual Basic > ASP.NET Empty Web Site > Click Ok
  4. Website > Add New Item > Web Form > Click Add
  5. Now Drag and Drop a “GridView” in Default aspx page from Data tab in Toolbox.
  6. Populate this GridView with data you want. I have populated it with “authors” table of “PUBS” database.
  7. The code in Default.aspx page will be like below

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="au_id" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="au_id" HeaderText="au_id" ReadOnly="True"
                SortExpression="au_id" />
            <asp:BoundField DataField="au_lname" HeaderText="au_lname"
                SortExpression="au_lname" />
            <asp:BoundField DataField="au_fname" HeaderText="au_fname"
                SortExpression="au_fname" />
            <asp:BoundField DataField="phone" HeaderText="phone"
                SortExpression="phone" />
            <asp:BoundField DataField="address" HeaderText="address"
                SortExpression="address" />
            <asp:BoundField DataField="city" HeaderText="city"
                SortExpression="city" />
            <asp:BoundField DataField="state" HeaderText="state"
                SortExpression="state" />
            <asp:BoundField DataField="zip" HeaderText="zip"
                SortExpression="zip" />
            <asp:CheckBoxField DataField="contract" HeaderText="contract"
                SortExpression="contract" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:PUBSConnectionString %>"
            SelectCommand="SELECT * FROM [authors]">
    </asp:SqlDataSource>


    I have populated the GridView from “authors” table in “PUBS” database using SqlDataSource. You can populate it according to your requirements.
     
  8. Now add a TemplateField in GridView and add a checkbox in the ItemTemplate of TemplateField.

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="au_id" DataSourceID="SqlDataSource1">
        <Columns>
        <asp:TemplateField>
           <ItemTemplate>
                <asp:CheckBox ID="CheckBox1" runat="server" />
           </ItemTemplate>
        </asp:TemplateField>
     
            <asp:BoundField DataField="au_id" HeaderText="au_id" ReadOnly="True"
                SortExpression="au_id" />
            <asp:BoundField DataField="au_lname" HeaderText="au_lname"
                SortExpression="au_lname" />
            <asp:BoundField DataField="au_fname" HeaderText="au_fname"
                SortExpression="au_fname" />
            <asp:BoundField DataField="phone" HeaderText="phone"
                SortExpression="phone" />
            <asp:BoundField DataField="address" HeaderText="address"
                SortExpression="address" />
            <asp:BoundField DataField="city" HeaderText="city"
                SortExpression="city" />
            <asp:BoundField DataField="state" HeaderText="state"
                SortExpression="state" />
            <asp:BoundField DataField="zip" HeaderText="zip"
                SortExpression="zip" />
            <asp:CheckBoxField DataField="contract" HeaderText="contract"
                SortExpression="contract" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:PUBSConnectionString %>"
            SelectCommand="SELECT * FROM [authors]">
    </asp:SqlDataSource>

     
    I have added a CheckBox control in ItemTemplate of TemplateField. This is because we want to select multiple rows in GridView control. We will get Checked rows in our code behind file and will delete rows from database.

     
  9.  At the end add a Button and a Label in Default.aspx page

    <asp:Button ID="Button1" runat="server" Text="Delete Selected Rows"
           onclick="Button1_Click" />
    <br />
    <asp:Label ID="Label1" runat="server" ></asp:Label>

     
  10. Write below function in code behind file to delete selected rows. Include following namespaces also.

    C#
     
    using System.Data;
    using System.Data.SqlClient;
     
     
    private void DeleteRow(string authorid)
    {
            string cmdText = "Delete from authors Where au_id ='" + authorid +"'";
            string connectionString = "Data Source=Local;Initial Catalog=PUBS;Integrated Security=True";
     
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();
        SqlCommand command = new SqlCommand(cmdText, connection);
        command.Parameters.Add("au_id", SqlDbType.VarChar, 11).Value = authorid;
        command.ExecuteNonQuery();
        connection.Close();
    }
     
    VB.NET
     
    Imports System.Data
    Imports System.Data.SqlClient
     
     
    Private Sub DeleteRow(ByVal authorid As String)
        Dim cmdText As String = "Delete from authors Where au_id ='" & authorid & "'"
        Dim connectionString As String = "Data Source=Local;Initial Catalog=PUBS;Integrated Security=True"
     
        Dim connection As New SqlConnection(connectionString)
        connection.Open()
        Dim command As New SqlCommand(cmdText, connection)
        command.Parameters.Add("au_id", SqlDbType.VarChar, 11).Value = authorid
        command.ExecuteNonQuery()
        connection.Close()
    End Sub
     
    I have written a function DeleteRow(). This function will make connection to SQL Server and delete one row at a time from the database table. It takes the autherid as parameter and deletes all columns of that that au_id in authors table. We will call this function for every GridView row where CheckBox is checked.
     
  11. Now add below code in button click event of code behind file

    C#
     
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gridviewrow in GridView1.Rows)
        {
            CheckBox checkbox = (CheckBox)gridviewrow.Cells[0].FindControl("CheckBox1");
     
            if (checkbox.Checked)
            {
                string autherid = (GridView1.DataKeys[gridviewrow.RowIndex].Value).ToString();
                DeleteRow(autherid);
                Label1.Text = "All Selected rows are deleted";
            }       
        }
    }
     
    VB.NET
     
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        For Each gridviewrow As GridViewRow In GridView1.Rows
            Dim checkbox As CheckBox = DirectCast(gridviewrow.Cells(0).FindControl("CheckBox1"), CheckBox)
     
            If checkbox.Checked Then
                Dim autherid As String = (GridView1.DataKeys(gridviewrow.RowIndex).Value).ToString()
                DeleteRow(autherid)
                Label1.Text = "All Selected rows are deleted"
            End If
        Next
    End Sub

    I have used a foreach loop to iterate through all GridView rows. We have to get the CheckBox control to get the checked items of the GridView. If the CheckBox is checked than we are getting the autherid using RowIndex method of GridViewRow object. Then we are calling the DeleteRow() function by passing the autherid for every checked row in GridViewRow.
     
  12. Press F5 and see website in browser.

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to use AJAX DropDownExtender in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net