Go to DotNetFunda.com
 Online : 237 |  Welcome, Guest!   Login
 
Home > Articles > ASP.NET > Multiple Delete From a gridview in one click.

  • Nominate yourself for "ADO.NET" online training session tomorrow (13-Mar-2010) for FREE, click here.

  • Download OOPS and ASP.NET Online training session video and PPT from here.

Submit Article | Articles Home | Search Articles |

Multiple Delete From a gridview in one click.

 Posted on: 8/10/2009 10:14:21 PM by Utsav | Views: 931 | Category: ASP.NET | Level: Beginner | Print Article
After Selecting the row or checking the multiple row in a Gridview you can delete the data in just one click.

.NET Training Videos!
Buy online comprehensive training video pack just for $35.00 only, see what's inside it.

Introduction

In this Article you can learn how to select the multiple values of row using checkboxes from a Gridview and delete it.





For this tutorial,

 

I have taken example of simple database named “Contact”.

 




I have written my connection string in web.config file under connectionStrings tag. My connection string to connect to the database looks like following.

 

<connectionStrings>

 

  <add name="CRMConnectionString1" connectionString="Data    Source=DataSource1 ;Initial Catalog=CRM;Integrated Security=True;Pooling=False user id=SampleUser; password=SampleUser;"

   providerName="System.Data.SqlClient" />

 

</connectionStrings>


Now Create a page named as Contacts.aspx and add the following code.

 

<form id="form1" runat="server">

    <div style="left:75px; position:absolute; top:45px;">

        <asp:Button ID="btnMultipleDelete" runat="server" Text="Delete"

            onclick="btnMultipleDelete_Click" />

    </div>

 

    <div style="left: 75px; position: absolute; top:75px;">

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ContactId"

            

            EmptyDataText="No Contacts Yet." CellPadding="4"

            ForeColor="#333333" GridLines="None">

            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />

            <Columns>

           

            <asp:TemplateField>

              <ItemTemplate>

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

              </ItemTemplate>

            </asp:TemplateField>

           

                <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />

                <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />

                <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />

                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />

               

               

            </Columns>

            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />

            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />

            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

            <AlternatingRowStyle BackColor="White" />

        </asp:GridView>

        </div>

       

        <div style="left:75px; position:absolute; top:500px;">

        <asp:Label ID="lblmessage" runat="server"></asp:Label>

        </div>

    </form>



After you write this code in Source view you can see the following Similar output in your Design view.






Now its time to write the C# code

 

Open the page Contacts.aspx.cs

And write following codes.

 

using System.Data.SqlClient;

 

public partial class Contacts : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            BindData();

        }

    }

 

private void BindData()

    {

string connStr = ConfigurationManager.ConnectionStrings["CRMConnectionString1"].ToString();

 

        SqlConnection conn = new SqlConnection(connStr);

 

       

 

SqlDataAdapter dAD = new SqlDataAdapter("SELECT FirstName, LastName, Email, Address FROM Contact ", conn);

 

        dAD.SelectCommand.CommandType = CommandType.Text;

 

        DataSet dSet = new DataSet();

 

        try

        {

            conn.Open();

 

            dAD.Fill(dSet, "Contact");

 

 

        }

        catch (Exception ee)

        {

            lblmessage.Text = ee.Message.ToString();

        }

 

        finally

        {

            GridView1.DataSource = dSet;

            GridView1.DataBind();

 

 

 

 

            conn.Close();

            dSet.Dispose();

            dAD.Dispose();

 

        }

 

    }



The above code Binds your data into the gridview.

After this write the following code  which makes you to select the row using the checkbox and deleting the selected row from gridview.

protected void btnMultipleDelete_Click(object sender, EventArgs e)

    {

 

 

string connStr = ConfigurationManager.ConnectionStrings["CRMConnectionString1"].ToString();

        SqlConnection conn = new SqlConnection(connStr);

 

        SqlCommand cmd = new SqlCommand("DELETE FROM Contact WHERE ContactId = @ContactId ", conn);

 

        cmd.CommandType = CommandType.Text;

 

 

try

        {

            conn.Open();

 

         foreach(GridViewRow r in GridView1.Rows)

            {

               

                CheckBox ck = (CheckBox)r.FindControl("chkRows");

              

 

                if(ck.Checked == true)

                {

       int contactid = Convert.ToInt32(GridView1.DataKeys[r.RowIndex].Value);

                  cmd.Parameters.AddWithValue("@ContactId", contactid);

                  cmd.ExecuteNonQuery();

                }

            }

        }

 

catch (Exception ee)

        {

            lblmessage.Text = ee.Message.ToString();

        }

        finally

        {

            conn.Close();

            cmd.Dispose();

        }

 

        GridView1.EditIndex = -1;

 

        BindData();

    }

}

 

that’s all in coding section. Now its time to view the output.

 

 

After You complete this tutorial. Your output looks similar to:

 

Conclusion

After Selecting the row or checking the multiple row you can delete the data in just one click.

 

Hope you enjoy the coding...

 

 




If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Interesting?   Share and Bookmark this kick it on DotNetKicks.com


Experience:1 year(s)
Home page:http://www.uts-chupakabras.blogspot.com
Member since:Wednesday, June 17, 2009
Level:Starter
Status: [Member]
Biography:I am working in the APCA Nepal as a Software Developer. Recently I am doing the project on asp.net with c# page language. My project tilte is "Event and contact management " in which different users working in their desk can make their events and entries, assign the task to others, upload their documents and share with others. You can find my same articles in http://www.uts-chupakabras.blogspot.com/ also.
 Latest post(s) from Utsav

   ◘ Password Reminder: Reset the password and send it to the user's provided mail address posted on 9/14/2009 1:34:20 AM
   ◘ Multiple Delete From a gridview in one click. posted on 8/10/2009 10:14:21 PM


Submit Article

About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)