ITFunda.Com
Your details are safeBuyer's Satisfaction
Contact Us
Welcome Guest | Register | Login Why online training? | Buyers FAQs | Testimonials | Contact us

Subscribe


Subscribe to Tutorials feed

Our Quality Professors


Our professors includes
Contact us for training ...

Training Timing availability

Timing in IST

Online training and Job Support slots are available in the morning & evening Indian Time Zone.

Contact us for any query.

Technology Tags


ADO.NET AdRotator ASP.NET ASP.NET-AJAX Authentication-and-Authorization---LoginView BulletedList Button Caching Calendar Chart CheckBoxList Cookies CSharp CSS Cusotm-Control Debugging-and-Tracing DetailsView DropDownList-and-ListBox DropDownList-and--ListBox Error-handling FileUpload Forms-Authentication GridView HiddenField HTML HyperLink Image ImageButton ImageMap Javascript jQuery jQuery-Ajax jQuery-Attributes jQuery-effects jQuery-Effects jQuery-Events jQuery-How-to-Solution jQuery-Manipulations jQuery-Selectors jQuery-Traversing Label-and-Literal LinkButton ListView Localization-and-Globalization Login LoginName LoginStatus LoginStatus-and-LoginName-and-other-controls LoginView MasterPage Menu Meta-tags Panel PlaceHolder RadioButtonList Repeater Security Session-Management TextBox Themes-and-Skins Url-Routing User-Control Validations visual-studio Webconfig Working-with-Files-and-Folders

Search Tutorials

Keyword
eg. asp.net

Announcements

More ...


 

How to delete multiple selected records from the GridView?


by: Itfunda Product Type: Tips and Tricks (Books) Technologies: ASP.NET  GridView 

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>
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();
}
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();
}
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.

OUTPUT



This post is the part of following product

.NET Tips and Tricks

.NET Tips and Tricks This ".NET How to Tips and Tricks" contains solutions of hundreds of technical problems that help you to develop real time .NET projects easily. It has following features
  • Video tutorials
  • Demo projects source code
  • eBook with to-the point explanations & output
prepared by Sheo Narayan (Microsoft MVP).

 Latest tutorials

 Posts from Itfunda

  • .NET Live Project training
    This course has been especially designed to help aspiring .net professionals and freshers to gain knowledge about solving real time project problems in best possible way. This training is conducted by Mr. Sheo Narayan (Ex Microsoft MVP and founder of www.DotNetFunda.com).
    | Final Price: Rs 15000.00/$250.00
    More details ...

  • ASP.NET 4 Online Training with C#
    ASP.NET 4.0 using C# - A comprehensive online training on ASP.NET 4.0 using Visual C# 2013. This training gives you real time scenario based knowledge on C#, ASP.NET and ASP.NET AJAX that help you to work on any kind of web development projects in .NET technologies. This training is delivered by Mr. Sheo Narayan (Ex Microsoft MVP). Suitable for Windows developer or a complete freshers in the IT Industry who know HTML, CSS and JavaScript.
    List Price: $350.00 Discount: 25.00% | Final Price: Rs 13125.00/$262.50
    More details ...


Share this to:




About Us | Contact Us | Partners | Privacy Policy | Terms and Conditions | Buyer's FAQs | Seller's FAQs | Currency Converter | Go Top

Notice: If you found someone plagiarising our content/materials, kinldy let us know.

© SN ITFunda Services LLP. Site design and layout is copyright to SN ITFunda Services LLP.
Copying or duplicating or mimicking the site design and layout is prohibited and will be treated as a legal offence and will be prosecuted.
Logos, company, product, service or other names used here if any are only for reference purposes and they may be respective owner's right or trademarks.