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

Submit Article | Articles Home | Search Articles |

Multiple Delete From a gridview in one click.

red flag  Posted on: 8/10/2009 10:14:21 PM by Utsav | Views: 1475 | Category: ASP.NET | Level: Beginner


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



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.

Found interesting? Add this to:

| More



Please Sign In to vote for this post.

 
Latest post(s) from Utsav

Latest Articles
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.

Submit Article

About Us | The Team | Advertise | Contact Us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 9/3/2010 4:06:44 AM