How to delete multiple selected records from the GridView?

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 20152 red flag
Rating: 5 out of 5  
 1 vote(s)

To delete multiple selected records from the GridView, we can follow this approach.

GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data.

Get hundreds of ASP.NET Tips and Tricks and ASP.NET Online training here.

In the previous article we learnt about How to add a button with custom command name and perform an operation?
In this article we shall learn how to delete multiple selected records from the GridView, we can follow this approach.

ASPX PAGE

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"

AllowPaging="true" DataKeyNames="AutoId">

<Columns>

<asp:TemplateField HeaderText="Select">

<ItemTemplate>

<asp:CheckBox ID="chkSelect" runat="server" />

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField HeaderText="AutoId" DataField="AutoId" />

<asp:BoundField HeaderText="First Name" DataField="FirstName" />

<asp:BoundField HeaderText="Last Name" DataField="LastName" />

<asp:TemplateField HeaderText="Is Active?">

<ItemTemplate>

<%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

<p><asp:Button ID="btnDelete" runat="server" Text="Delete Selected Records"

OnClick="DeleteSelectedRecords" /></p>

In the above code snippet, we have a GridView that is almost similar to “MultipleSelection.aspx” page. The first column’s checkbox is used to select the record. On click of “Delete Selected Records” button we have attached “DeleteSelectedRecords” server side method that loops through the rows of the GridView and finds the checbox, if the checkbox is checked then that record is deleted from the database using ADO.NET code and then using GetData() method the record is re-populated to the GridView.

CODE BEHIND

 

string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

this.GetData();

}

}

private void GetData()

{

DataTable table = new DataTable();

// get the connection

using (SqlConnection conn = new SqlConnection(_connStr))

{

// write the sql statement to execute

string sql = "SELECT AutoId, FirstName, LastName, Age, Active FROM PersonalDetail ORDER By AutoId";

// instantiate the command object to fire

using (SqlCommand cmd = new SqlCommand(sql, conn))

{

// get the adapter object and attach the command object to it

using (SqlDataAdapter ad = new SqlDataAdapter(cmd))

{

// fire Fill method to fetch the data and fill into DataTable

ad.Fill(table);

}

}

}

GridView1.DataSource = table;

GridView1.DataBind();

}

/// <summary>

/// Gets the selected records.

/// </summary>

/// <param name="sender">The sender.</param>

/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>

protected void DeleteSelectedRecords(object sender, EventArgs e)

{

Response.Write("<h3>Selected records</h3>");

foreach (GridViewRow row in GridView1.Rows)

{

CheckBox chk = (CheckBox)row.FindControl("chkSelect");

if (chk.Checked)

{

int autoId =

int.Parse(GridView1.DataKeys[row.RowIndex].Value.ToString());

// get the selected AutoId and cells text

Response.Write("<p>AutoId: " + autoId + " deleted</p>");

// fire your DELETE method from BAL or service layer

using (SqlConnection conn = new SqlConnection(_connStr))

{

string sql = "Delete from PersonalDetail" + " where AutoId = @AutoId";

using (SqlCommand cmd = new SqlCommand(sql, conn))

{

cmd.Parameters.AddWithValue("@AutoId", autoId);

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

}

}

}

}

// repopulate the fresh data

this.GetData();

}

}

OUTPUT

Thanks for reading, hope you liked it.

Keep reading my forth coming articles. To read my series of articles on ASP.NET,click here.

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)