Click here to Skip to main content
15,867,834 members
Articles / DevOps / Load Testing
Tip/Trick

Deleting Multiple Rows in GridView in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
18 Jun 2012CPOL 42.2K   1.1K   6   3
The GridView control in ASP.NET is used to represent information from a database in tabular format.

Introduction

The GridView control in ASP.NET is used to represent the information of database in a tabular format. This table format of information is used by developers so they can access large amounts of  information in minimum time. The operations that can be performed with GridView information include inserting new information, updating, deleting, and representing data with appropriate keywords. Today in this article I will show you how to delete multiple Rows/Records from a GridView. I have used a user defined column of type CheckBox control in the GridView, so the user can select multiple rows that he wants to delete.

Using the code

Aspx.cs page code:
C#
Page_Load(object sender, EventArgs e)
{
    Label2.Text = "Remove Multiple Rows Records Gridview CheckBox before Confirmation";
    if (!IsPostBack)
    {
        bindData();
    }
}

private void bindData()
{
    try
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=.\\SQLEXPRESS; AttachDBFilename" + 
            "=|DataDirectory|paging.mdf; Integrated Security=True;User Instance=True";
        SqlCommand com = new SqlCommand();
        com.Connection = con;
        com.CommandText = "customerSelect";
        com.CommandType = CommandType.StoredProcedure;
        con.Open();
        SqlDataReader sdr = com.ExecuteReader();
       DataTable dt = new DataTable();
        dt.Load(sdr);
         GridView1.DataSource = dt;
        GridView1.DataBind();
        con.Close();

    }
    catch (Exception ex)
    {
        lblError.Text = ex.ToString();
    }

}

On Delete Button Click

C#
Protected void btnDelete_Click(object sender, EventArgs e)
{
 try
 {
   StringCollection idCollection = new StringCollection();
   string strID = string.Empty;
   for(int i = 0; i < GridView1.Rows.Count; i++)
   {
     CheckBox chkDelete = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chkSelect");
     if(chkDelete != null)
     {
      if(chkDelete.Checked)
      {
        strID = GridView1.Rows[i].Cells[1].Text;
        idCollection.Add(strID);
      }
     }
   }
  if(idCollection.Count > 0)
  {
    DeleteMultipleRecords(idCollection);
    GridView1.DataBind();
  }
  else
  {
  lblError.Text = "Please select any row to delete";
  }
 }
 catch(Exception ex)
 {
  lblError.Text = ex.ToString();
 }
}

private void DeleteMultipleRecords(StringCollection idCollection)
{
 try
 {
   SqlConnection con = new SqlConnection();
   con.ConnectionString = "Data Source=.\\SQLEXPRESS; AttachDBFilename=" + 
       "|DataDirectory|paging.mdf;Integrated Security=True;User Instance=True";
   SqlCommand com = new SqlCommand();
   string IDs = "";
   foreach(string id in idCollection)
   {
    IDs += id.ToString() + ",";
   }
   try
   {
    string test = IDs.Substring (0, IDs.LastIndexOf(","));
    string sql = "DELETE FROM CUSTOMERS Where ID IN(test)";
    com.CommandType = CommandType.Text;
    com.CommandText = sql;
    com.Connection = con;
    con.Open();
    com.ExecuteNonQuery();
   }
   catch(SqlException ex)
   {
     string errorMsg = "Error in Deletion";
     errorMsg += ex.Message;
     throw new Exception(errorMsg);
   }
   finally
   {
    con.Close();
   }
 }
 catch( Exception ex)
 {
 lblError.Text = ex.ToString();
 }
 bindData();
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
A software Developer. Hold Master in Computer Application with Honor. Feel free to ask any question about .NET. I am running my own website for aspnet users. www.dotnetaid.com

Comments and Discussions

 
QuestionGRIDVIEW QUESTION Pin
dbccjhsbchjsabchjbs20-Jun-12 0:17
dbccjhsbchjsabchjbs20-Jun-12 0:17 
AnswerRe: GRIDVIEW QUESTION Pin
sourabhdev147-Feb-13 20:05
sourabhdev147-Feb-13 20:05 
QuestionSQL calls Pin
wiredeye18-Jun-12 5:42
wiredeye18-Jun-12 5:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.