Search
Categories
  ASP.NET
Visual C#
Visual Basic
.NET Framework
ADO.NET
AJAX
LINQ
Java
 
Tutorial Rating
 
2.9 out of 5


Total Votes: 49
         
1 2 3 4 5
 




Deleting multiple Rows in GridView using Checkbox

Author: Waqas Anwar - Posted Date: 03-June-2009 - Category: ASP.NET   
Bookmark and Share
In one of my other article “Using Checkbox in ASP.NET GridView Control”, I have shown you how you can update the row status in database using checkboxes in GridView. There are situations when you want to provide checkboxes in GridView for deleting multiple database records similar to Hotmail or Yahoo inboxes. GridView control allows you to delete only a single record at a time but in this tutorial I will show you how you can implement multiple records deletion scenario in GridView control.
 
Delete multiple rows in GridView

To start this tutorial you add the GridView and Button controls on ASP.NET page and make sure your code looks similar to following:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="40%">
   <Columns>
      <asp:TemplateField HeaderText="Delete">
         <ItemTemplate>
            <asp:CheckBox runat="server" ID="chkDelete" />
         </ItemTemplate>
      </asp:TemplateField>

     
      <asp:BoundField DataField="ProductID" HeaderText="Product ID">
         <HeaderStyle HorizontalAlign="Center" />
         <ItemStyle HorizontalAlign="Center" />
      </asp:BoundField>
     
      <asp:BoundField DataField="ProductName" HeaderText="Product Name">
         <HeaderStyle HorizontalAlign="Left" />
         <ItemStyle HorizontalAlign="Left" />
      </asp:BoundField>
   </Columns>
</asp:GridView>

        <br />
<asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click" Text="Delete Selected Records" />

The code above is straight forward and the important thing is the use of TemplateField to add a CheckBox control in every row of the GridView control. The data is provided to GridView control in the Page_Load event as follows:
protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      BindData();

      btnDelete.Attributes.Add("onclick",
         "return confirm('Are you sure you want to delete selected item(s) ?');");

   }
}

private void BindData()
{
   string constr = @"Server=TestServer; Database=SampleDB; uid=test; pwd=test;";
   string query = @"SELECT * FROM Products";

   SqlDataAdapter da = new SqlDataAdapter(query, constr);
   DataTable table = new DataTable();

   da.Fill(table);

   GridView1.DataSource = table;
   GridView1.DataBind();
}

Notice how I added Delete confirmation to the button using the Attributes collection in the Page_Load event. The rest of the code is binding the GridView to a Products table using the SqlDataAdapter and DataTable classes available in ADO.NET. If you will test your page you will see GridView with checkboxes similar to the figure shown above in the start of the tutorial. Now you have to write code on the Click event of the Button in which you need to check which products are selected for deletion. Following is the code for Delete button click event:
protected void btnDelete_Click(object sender, EventArgs e)
{
   ArrayList productsToDelete = new ArrayList();
  
   foreach (GridViewRow row in GridView1.Rows)
   {
      if (row.RowType == DataControlRowType.DataRow)
      {
         CheckBox chkDelete = (CheckBox)row.Cells[0].FindControl("chkDelete");

         if (chkDelete != null)
         {
            if (chkDelete.Checked)
            {
               string productId = row.Cells[1].Text;
               productsToDelete.Add(productId);
            }
         }
       }
   }

   DeleteProducts(productsToDelete);
   BindData();
}

In the above code I first created an ArrayList to store product id for all the selected products used has selected to delete. Then I am running a simple foreach loop to iterate all the rows in the GridView. Remember we are only interested in the rows where we have checkboxes we are not interested in Header, Footer or Pager rows that’s why I put one if condition check in the loop to make sure we only process data rows. Then I am getting the reference of every single CheckBox in the GridView using Cells collection and FindControl method. After I have Checkbox control available I am checking whether it is checked or not using Checked property and if it is checked I am reading Product ID of that product in second cell in the same row. I am also storing the product id in the productsToDelete ArrayList for later processing. Once the foreach loop is finished I called a custom method DeleteProducts and passed the productsToDelete ArrayList to the method. I am not implementing the code for DeleteProducts method but you can implement it easily once you know which items are available to delete from the database. The declaration of DeleteProducts will be similar to following:

private void DeleteProducts(ArrayList productsToDelete)
{

   // Execute SQL DELETE Command to Delete all Products
   // available in productsToDelete collection

   // You can also pass productsToDelete ArrayList to
   // your Data Access Layer component for delete operation
}

I hope you will be able to implement this scenario in your own ASP.NET website easily without facing any big issue.
 






RELATED TUTORIALS

  Displaying Total in Footer of GridView
  Using Button columns in GridView
  Editing Data using ASP.NET GridView Control
  Using Checkbox in ASP.NET GridView Control
  Formatting GridView output based on Data
  Display Microsoft Excel File in ASP.NET GridView
  Export ASP.NET GridView to Excel
  Using Hyperlink columns in GridView

LEAVE YOUR COMMENTS LEAVE YOUR COMMENTS
 Name (required)  
 Email (required
 Website


 
POSTED COMMENTS POSTED COMMENTS

i am satisfy
Posted by kumar on Thursday, June 11, 2009

good code
Posted by iiiiii on Thursday, June 11, 2009

Very Good Code
Posted by Narinder on Friday, October 16, 2009

Hello , i want to use short cut key of keyboard for deletion of records. can anyone help me?
Posted by jaykumar on Friday, November 20, 2009

You can use java script to attach short cut keys with buttons. I also
remember there is property to attach short cut keys with ASP.NET buttons.
I think its AccessKey property.
Posted by Waqas Anwar on Friday, November 20, 2009

Thank You for Your Code
Posted by banyar on Thursday, December 03, 2009

can you please provide me code for inserting rows into sql in grid view using checkbox
Posted by abhinav on Tuesday, March 02, 2010

Thank for your intruction
Can you write detail DeleteProducts method ? I still dont understand.
Posted by Tony on Monday, May 03, 2010

Thank for your intruction
Can you write detail DeleteProducts method ? I still dont understand.
Posted by Tony on Monday, May 03, 2010

 


 
 
 

Categories

My Portfolio

Website Links


Copyright @ 2009 EzzyLearning.com