71
dd delete update inside gridview using store procedure in ASP.NET Code for .aspx page: <table class="style1"> <tr> <td class="style2"> Album Name</td> <td> <asp:TextBox ID="txt_album_name" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txt_album_name" ErrorMessage="Please enter the album name"></asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style2"> Caption</td> <td> <asp:TextBox ID="txt_caption" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txt_caption" ErrorMessage="Please enter the caption"></asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style2"> Image</td> <td> <asp:FileUpload ID="FileUpload1" runat="server" />

gridview

Embed Size (px)

DESCRIPTION

gridview

Citation preview

Page 1: gridview

dd delete update inside gridview using store procedure in ASP.NET

Code for .aspx page:<table class="style1">        <tr>            <td class="style2">                Album Name</td>            <td>                <asp:TextBox ID="txt_album_name" runat="server"></asp:TextBox>                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"                     ControlToValidate="txt_album_name" ErrorMessage="Please enter the album name"></asp:RequiredFieldValidator>            </td>        </tr>        <tr>            <td class="style2">                Caption</td>            <td>                <asp:TextBox ID="txt_caption" runat="server"></asp:TextBox>                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"                     ControlToValidate="txt_caption" ErrorMessage="Please enter the caption"></asp:RequiredFieldValidator>            </td>        </tr>        <tr>            <td class="style2">                Image</td>            <td>                <asp:FileUpload ID="FileUpload1" runat="server" />                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"                     ControlToValidate="FileUpload1" ErrorMessage="Please browse the image"></asp:RequiredFieldValidator>            </td>        </tr>        <tr>            <td class="style3">                </td>            <td class="style4">                <asp:Button ID="btn_insert" runat="server" onclick="btn_insert_Click"                     Text="Insert" />            </td>        </tr>        <tr>            <td class="style2" colspan="2">                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

Page 2: gridview

                    onrowcancelingedit="GridView1_RowCancelingEdit"                     onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"                     onrowupdating="GridView1_RowUpdating"                     onselectedindexchanging="GridView1_SelectedIndexChanging">                    <Columns>                    <%--here i am using templatefields to for binding the gridview--%>                        <asp:TemplateField HeaderText="Album_name">                            <EditItemTemplate>                                                 <%--here i am using the textbox in the edititmtemplatefield to upadate the data--%>                                <asp:TextBox ID="txt_album_name" runat="server"                                     Text='<%# Eval("album_name") %>'></asp:TextBox>                                <asp:Label ID="Label4" runat="server" Text='<%# Eval("id") %>' Visible="False"></asp:Label>                            </EditItemTemplate>                            <ItemTemplate>                                <asp:Label ID="Label1" runat="server" Text='<%# Eval("album_name") %>'></asp:Label>                                <asp:Label ID="Label2" runat="server" Text='<%# Eval("id") %>' Visible="False"></asp:Label>                            </ItemTemplate>                        </asp:TemplateField>                        <asp:TemplateField HeaderText="Caption">                            <EditItemTemplate>                                <asp:TextBox ID="txt_caption" runat="server" Text='<%# Eval("caption") %>'></asp:TextBox>                            </EditItemTemplate>                            <ItemTemplate>                                <asp:Label ID="Label3" runat="server" Text='<%# Eval("caption") %>'></asp:Label>                            </ItemTemplate>                        </asp:TemplateField>                        <asp:TemplateField HeaderText="Image">                        <ItemTemplate>                        <%--for displaying the image inside the gidview here i'm using the <img>tag                        and specify the path of the folder where image is stored--%>                        <img alt ="" src ='images/<%#Eval("image") %>' height="50px" width="50px"/>                        </ItemTemplate>                        </asp:TemplateField>                        <asp:TemplateField HeaderText="Delete">                        <%--here i am using the linkbutton to delete the record and specify the command name                        of this linkbutton is delete--%>                            <ItemTemplate>

Page 3: gridview

                                <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"                                     CommandName="Delete"                                     onclientclick="return confirm('are you sure you want to delet this column')">Delete</asp:LinkButton>                            </ItemTemplate>                        </asp:TemplateField>                        <asp:TemplateField HeaderText="Update">                            <EditItemTemplate>                           <%-- here i am using the s linkbuttons to update the record and a  cancel button                           and set the commandname of update button is update and the cancel button is cancel --%>                                <asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False"                                     CommandName="Update">Update</asp:LinkButton>                                <asp:LinkButton ID="LinkButton4" runat="server" CausesValidation="False"                                     CommandName="Cancel">Cancel</asp:LinkButton>                            </EditItemTemplate>                            <ItemTemplate>                               <%--here i am using the linkbutton for edit and specify the command name                        of this linkbutton is Edit--%>                                <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"                                     CommandName="Edit">Edit</asp:LinkButton>                            </ItemTemplate>                        </asp:TemplateField>                    </Columns>                </asp:GridView>            </td>        </tr>        </table>

Code for aspx.cs page:

using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;

Page 4: gridview

using System.Xml.Linq;// use below two namespaces for this programusing System.Data.SqlClient;using System.IO;

public partial class Gallery : System.Web.UI.Page{    // here i declare some variables that will be used below inside the code.    String fn;    String path;    SqlConnection cnn = new SqlConnection();    SqlCommand cmd = new SqlCommand();    SqlDataAdapter adp;    DataTable dt;    Int32 id;// id as a integer variable it will be used to catch the id at the time of    //the deletion and updation inside the gridview.    // below  the two string variables will be used to update the record , inside the gridvbiew    String album_name;     String caption;     // the image this string type variable will be used to delete the image from the folder where    //the image will be stored after the record insertion.     String image;

    protected void Page_Load(object sender, EventArgs e)    {        //here i declare the connection of the connectionstring to attach the database with the application        cnn.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;        cnn.Open();        // if the connection will be closed the below code open the connection when the page will be loaded.        if (cnn.State == ConnectionState.Closed)        {            cnn.Open();        }        cnn.Close();

        if (IsPostBack == false)        {            // here i am calling the function that will bind the gridview            grd_bind();        }    }

    protected void btn_insert_Click(object sender, EventArgs e)

Page 5: gridview

    {        // inside the first if condition i am declaring the code for the uploading the image.         if (FileUpload1.PostedFile.ContentLength > 0)        {            fn = Path.GetFileName(FileUpload1.FileName);            path = Server.MapPath("images") + "/" + fn;            FileUpload1.SaveAs(path);        }        if (cnn.State == ConnectionState.Closed)        {            cnn.Open();        }        // here i am using the store procedure named tb_gallery_insert to insert the record inside the database.        SqlCommand cmd = new SqlCommand("tb_gallery_insert", cnn);        cmd.CommandType = CommandType.StoredProcedure;        cmd.Connection = cnn;        // here i am passing the parameters to insert the record        cmd.Parameters.AddWithValue("@album_name", txt_album_name.Text);        cmd.Parameters.AddWithValue("@caption", txt_caption.Text);        cmd.Parameters.AddWithValue("@image", fn);        cmd.ExecuteNonQuery();        cmd.Dispose();        grd_bind();        cnn.Close();        //here i am calling the function that  will be used after the insertion of the record         //insert the record inside the database.        clr();    }    // this function will used after the insertion of the record insert the record inside the database.    private void clr()    {        txt_album_name.Text = "";        txt_caption.Text = "";    }    //this function will used to bind the gridview    private void grd_bind()    {        if (cnn.State == ConnectionState.Closed)        { cnn.Open(); }        // here i am using the sql query to select the gecord from the database and         adp = new SqlDataAdapter("SELECT * FROM tb_gallery ", cnn);        // here i declare the datatable to fill the record        dt = new DataTable();        // here  i am filling the dqldataadapter withe the datatable dt        adp.Fill(dt);

Page 6: gridview

        // here i am disposing the apd after filling the record        adp.Dispose();        // here i am binding the ghridview with the datatable dt        GridView1.DataSource = dt;        GridView1.DataBind();            }    // this is a gridview's rowdeleting event that will be used to delete of the row  record from the database    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)    {                try        {            if (cnn.State == ConnectionState.Closed)            {                cnn.Open();            }            //inside the id variable i am finding the label from the gridview and with the help of this             //label i will fetch the id of the record that i want to delete            id = Convert.ToInt32(((Label)(GridView1.Rows[e.RowIndex].FindControl("label2"))).Text);            // here i am using the tb_gallery_delete store procedure ti delete the record from the database            SqlCommand cmd = new SqlCommand("tb_gallery_delete", cnn);            cmd.CommandType = CommandType.StoredProcedure;            cmd.Connection = cnn;            cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;            // this code will be used to delete the image from the folder too            // here i am using the sql query to select the record that will be selected by the user for deletion            SqlDataAdapter adp = new SqlDataAdapter("select * from tb_gallery where id=@id", cnn);            // here i am passing the parameter that will be used by the above sql query named as id            adp.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = id;            DataSet ds = new DataSet();            // here i am filling the sqldataadapter with the dataset dt            adp.Fill(ds);            try            {                // here i am using the try catch exception becoz if the image will be not available                 // in side the folder. it does not creates the error.                // inside the image variable i am fetching the image path from the database                image = Convert.ToString(ds.Tables[0].Rows[0]["image"]);                // this line will used to delete the image from the folder

Page 7: gridview

                // here i am also giving the filder name where you image was stored.                File.Delete(Server.MapPath("images") + "\\" + image);            }            catch { }            cmd.ExecuteNonQuery();            cmd.Dispose();            grd_bind();        }        catch {                 }

    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)    {        GridView1.EditIndex = -1;        grd_bind();    }    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)    {        GridView1.EditIndex = e.NewEditIndex;        grd_bind();    }    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)    {        if (cnn.State == ConnectionState.Closed)        {            cnn.Open();        }

        //inside the id variable i am finding the label from the gridview and with the help of this         //label i will fetch the id of the record that i want to update        id = Convert.ToInt32(((Label)(GridView1.Rows[e.RowIndex].FindControl("label4"))).Text);        //inside the album_name variable i am finding the textbox from the gridview and with the help of this         //textbox i will find the album name thatthe user want to update        album_name = (((TextBox)(GridView1.Rows[e.RowIndex].FindControl("txt_album_name"))).Text);        //inside the caption  variable i am finding the textbox from the gridview and with the help of this         //textbox i will find caption that the user want to update        caption = (((TextBox)(GridView1.Rows[e.RowIndex].FindControl("txt_caption"))).Text);

Page 8: gridview

        // here i am using the tb_gallery_update to update the record from the database inside the gridview        SqlCommand cmd = new SqlCommand("tb_gallery_update", cnn);        cmd.CommandType = CommandType.StoredProcedure;        cmd.Connection = cnn;        // here i am passing the three variables that will be used to update the record by the store orocedure        cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;        cmd.Parameters.Add("@album_name", SqlDbType.VarChar, 50).Value = album_name;        cmd.Parameters.Add("@caption", SqlDbType.VarChar, 50).Value = caption;        cmd.ExecuteNonQuery();        cmd.Dispose();        GridView1.EditIndex = -1;        // here i am also calling the function taht will bind the gridview after fetching the record        //from the database        grd_bind();    }

    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)    {        GridView1.PageIndex = e.NewSelectedIndex;        grd_bind();    }}

See output in this image:

Page 9: gridview

Sql Script for database:

SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_Gallery]') AND type in (N'U'))BEGINCREATE TABLE [dbo].[tb_Gallery](      [id] [int] IDENTITY(1,1) NOT NULL,      [Album_name] [varchar](50) NULL,      [Caption] [varchar](50) NULL,      [Image] [varchar](50) NULL) ON [PRIMARY]ENDGOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_gallery_insert]') AND type in (N'P', N'PC'))BEGINEXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[tb_gallery_insert]       @album_name varchar(50),       @caption varchar(50),     @image varchar(50)AS      insert into tb_gallery values(@album_name,@caption,@image)      RETURN' ENDGOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_gallery_delete]') AND type in (N'P', N'PC'))BEGINEXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[tb_gallery_delete]      @id intAS      delete from tb_gallery where id=@id      RETURN' ENDGOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO

Page 10: gridview

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_gallery_update]') AND type in (N'P', N'PC'))BEGINEXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[tb_gallery_update]      @id int,      @album_name varchar(50),      @caption varchar(50)AS      update tb_gallery set album_name=@album_name, caption=@caption where id=@id      RETURN' END

 GridView - Add Edit Update Delete and Paging the AJAX wayYou might have seen many articles explaining ASP.Net GridView Add (Insert), Edit, Update and Delete functionality, but this is different and how I’ll explain as we progress. My main objective in this article is to keep it simple and cover multiple aspects in one article.

 

Concept

Basically I have tried to make the normal Add (Insert), Edit, Update and delete functions in ASP.Net GridView simple and also combining the powers of ASP.Net AJAX with that of JQuery to give an elegant and charming user experience.

 

Database and Connection String         

For this article as usual I have used my favorite NorthWind database which you can get by clicking on the link below.

Download Northwind Database

Below is the connection string from the web.config

<connectionStrings>      <add name="conString" connectionString="Data Source=.\SQLExpress;      database=Northwind;Integrated Security=true"/></connectionStrings>

 

The GridView

Below is the markup of the ASP.Net GridView control that I’ll be using to demonstrate the various features explained in this article.

 

<div id = "dvGrid" style ="padding:10px;width:550px"><asp:UpdatePanel ID="UpdatePanel1" runat="server">

Page 11: gridview

<ContentTemplate><asp:GridView ID="GridView1" runat="server"  Width = "550px"AutoGenerateColumns = "false" Font-Names = "Arial" Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"  HeaderStyle-BackColor = "green" AllowPaging ="true"  ShowFooter = "true"  OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer"onrowupdating="UpdateCustomer"  onrowcancelingedit="CancelEdit"PageSize = "10" ><Columns><asp:TemplateField ItemStyle-Width = "30px"  HeaderText = "CustomerID">    <ItemTemplate>        <asp:Label ID="lblCustomerID" runat="server"         Text='<%# Eval("CustomerID")%>'></asp:Label>    </ItemTemplate>     <FooterTemplate>        <asp:TextBox ID="txtCustomerID" Width = "40px"             MaxLength = "5" runat="server"></asp:TextBox>    </FooterTemplate> </asp:TemplateField> <asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Name">    <ItemTemplate>        <asp:Label ID="lblContactName" runat="server"                 Text='<%# Eval("ContactName")%>'></asp:Label>    </ItemTemplate>    <EditItemTemplate>        <asp:TextBox ID="txtContactName" runat="server"             Text='<%# Eval("ContactName")%>'></asp:TextBox>    </EditItemTemplate>      <FooterTemplate>        <asp:TextBox ID="txtContactName" runat="server"></asp:TextBox>    </FooterTemplate> </asp:TemplateField><asp:TemplateField ItemStyle-Width = "150px"  HeaderText = "Company">    <ItemTemplate>        <asp:Label ID="lblCompany" runat="server"             Text='<%# Eval("CompanyName")%>'></asp:Label>    </ItemTemplate>    <EditItemTemplate>        <asp:TextBox ID="txtCompany" runat="server"             Text='<%# Eval("CompanyName")%>'></asp:TextBox>    </EditItemTemplate>      <FooterTemplate>        <asp:TextBox ID="txtCompany" runat="server"></asp:TextBox>    </FooterTemplate> </asp:TemplateField><asp:TemplateField>    <ItemTemplate>        <asp:LinkButton ID="lnkRemove" runat="server"             CommandArgument = '<%# Eval("CustomerID")%>'          OnClientClick = "return confirm('Do you want to delete?')"        Text = "Delete" OnClick = "DeleteCustomer"></asp:LinkButton>    </ItemTemplate>    <FooterTemplate>        <asp:Button ID="btnAdd" runat="server" Text="Add"             OnClick = "AddNewCustomer" />    </FooterTemplate> </asp:TemplateField>

Page 12: gridview

<asp:CommandField  ShowEditButton="True" /> </Columns> <AlternatingRowStyle BackColor="#C2D69B"  /></asp:GridView> </ContentTemplate> <Triggers><asp:AsyncPostBackTrigger ControlID = "GridView1" /> </Triggers> </asp:UpdatePanel> </div>

 

The GridView has 3 data columns

1. Customer ID

2. Contact Name

3. Company Name

I have added a LinkButton in 4th column which will act as custom column for delete functionality. The reason to use a custom button is to provide the JavaScript confirmation box to the user when he clicks Delete. For Edit and Update I have added a command field which will act as the 5th column.

There’s also a Footer Row with 3 TextBoxes which will be used to add new records to the database and an Add button which will be used to add the records.

I have enabled pagination and finally wrapped the complete Grid in update panel and the update panel in a div dvGrid and the reason to that I’ll explain later in the article

 

Binding the GridView

Below is the code to bind the GridView in the page load event of the page

 C#  private String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;protected void Page_Load(object sender, EventArgs e){    if (!IsPostBack)    {        BindData();    }}

private void BindData(){    string strQuery = "select CustomerID,ContactName,CompanyName" +                       " from customers";    SqlCommand cmd = new SqlCommand(strQuery);    GridView1.DataSource = GetData(cmd);    GridView1.DataBind();

Page 13: gridview

VB.Net

Private strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionStringProtected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load   If Not IsPostBack Then         BindData()   End IfEnd Sub

Private Sub BindData()  Dim strQuery As String = "select CustomerID,ContactName,CompanyName" & _                                " from customers"  Dim cmd As New SqlCommand(strQuery)  GridView1.DataSource = GetData(cmd)  GridView1.DataBind()End Sub

 

Below is the screenshot of the GridView being populated using the above code

Page 14: gridview

 

Adding new record

As discussed above I have placed 3 textboxes and a button in the Footer Row of the ASP.Net GridView control in order to add new record to the database. On the onclick event if the button the records are inserted into the SQL Server Database and the GridView is updated

 

C#

protected void AddNewCustomer(object sender, EventArgs e){  string CustomerID=((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;   string Name = ((TextBox)GridView1.FooterRow.FindControl("txtContactName")).Text;

Page 15: gridview

  string Company = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;   SqlConnection con = new SqlConnection(strConnString);  SqlCommand cmd = new SqlCommand();  cmd.CommandType = CommandType.Text;  cmd.CommandText = "insert into customers(CustomerID, ContactName, CompanyName) " +  "values(@CustomerID, @ContactName, @CompanyName);" +  "select CustomerID,ContactName,CompanyName from customers";  cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID;  cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name;  cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company;  GridView1.DataSource = GetData(cmd);  GridView1.DataBind(); }

 

VB.Net

Protected Sub AddNewCustomer(ByVal sender As Object, ByVal e As EventArgs)   Dim CustomerID As String = DirectCast(GridView1.FooterRow _                .FindControl("txtCustomerID"), TextBox).Text   Dim Name As String = DirectCast(GridView1 _                .FooterRow.FindControl("txtContactName"), TextBox).Text   Dim Company As String = DirectCast(GridView1 _                .FooterRow.FindControl("txtCompany"), TextBox).Text   Dim con As New SqlConnection(strConnString)   Dim cmd As New SqlCommand()   cmd.CommandType = CommandType.Text   cmd.CommandText = "insert into customers(CustomerID, ContactName, " & _        "CompanyName) values(@CustomerID, @ContactName, @CompanyName);" & _        "select CustomerID,ContactName,CompanyName from customers"   cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID   cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name   cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company   GridView1.DataSource = GetData(cmd)   GridView1.DataBind()End Sub 

You will notice I am firing two queries one to insert the data and second to select the updated data and then rebind the GridView. The figure below displays how new records are added.

 

Page 16: gridview

 

Edit and Update existing records

As described above I have used command field in order to provide the Edit functionality. Below is the code snippet which is used to edit and update the records

 

C#

protected void EditCustomer(object sender, GridViewEditEventArgs e){    GridView1.EditIndex = e.NewEditIndex;    BindData();}protected void CancelEdit(object sender, GridViewCancelEditEventArgs e){    GridView1.EditIndex = -1;    BindData();}protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e){    string CustomerID = ((Label)GridView1.Rows[e.RowIndex]                        .FindControl("lblCustomerID")).Text;    string Name = ((TextBox)GridView1.Rows[e.RowIndex]                        .FindControl("txtContactName")).Text;    string Company = ((TextBox)GridView1.Rows[e.RowIndex]                        .FindControl("txtCompany")).Text;    SqlConnection con = new SqlConnection(strConnString);    SqlCommand cmd = new SqlCommand();    cmd.CommandType = CommandType.Text;    cmd.CommandText = "update customers set ContactName=@ContactName," +

Page 17: gridview

     "CompanyName=@CompanyName where CustomerID=@CustomerID;" +     "select CustomerID,ContactName,CompanyName from customers";    cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID;    cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name;    cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company;    GridView1.EditIndex = -1;    GridView1.DataSource = GetData(cmd);    GridView1.DataBind(); }

 

            VB.Net

Protected Sub EditCustomer(ByVal sender As Object, ByVal e As GridViewEditEventArgs)   GridView1.EditIndex = e.NewEditIndex   BindData()End SubProtected Sub CancelEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)   GridView1.EditIndex = -1   BindData()End SubProtected Sub UpdateCustomer(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)   Dim CustomerID As String = DirectCast(GridView1.Rows(e.RowIndex) _                                .FindControl("lblCustomerID"), Label).Text   Dim Name As String = DirectCast(GridView1.Rows(e.RowIndex) _                                .FindControl("txtContactName"), TextBox).Text   Dim Company As String = DirectCast(GridView1.Rows(e.RowIndex) _                                .FindControl("txtCompany"), TextBox).Text   Dim con As New SqlConnection(strConnString)   Dim cmd As New SqlCommand()   cmd.CommandType = CommandType.Text   cmd.CommandText = "update customers set ContactName=@ContactName," _   & "CompanyName=@CompanyName where CustomerID=@CustomerID;" _   & "select CustomerID,ContactName,CompanyName from customers"   cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID   cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name   cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company   GridView1.EditIndex = -1   GridView1.DataSource = GetData(cmd)   GridView1.DataBind()End Sub

 

You can view above I am simply getting the data from the textboxes in the Footer Row and then firing an update query along with the select query so that the ASP.Net GridView control is also updated. The figure below displays the Edit and Update functionality.

 

Page 18: gridview

 

Deleting existing record with Confirmation

As said above I am using custom delete button instead of ASP.Net GridView delete command field and the main reason for that is to add a confirmation.

 

       C#

protected void DeleteCustomer(object sender, EventArgs e){    LinkButton lnkRemove = (LinkButton)sender;    SqlConnection con = new SqlConnection(strConnString);    SqlCommand cmd = new SqlCommand();    cmd.CommandType = CommandType.Text;    cmd.CommandText = "delete from  customers where " +    "CustomerID=@CustomerID;" +     "select CustomerID,ContactName,CompanyName from customers";    cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value         = lnkRemove.CommandArgument;    GridView1.DataSource = GetData(cmd);    GridView1.DataBind(); }

 

VB.Net

Protected Sub DeleteCustomer(ByVal sender As Object, ByVal e As EventArgs)   Dim lnkRemove As LinkButton = DirectCast(sender, LinkButton)

Page 19: gridview

   Dim con As New SqlConnection(strConnString)   Dim cmd As New SqlCommand()   cmd.CommandType = CommandType.Text   cmd.CommandText = "delete from customers where " & _   "CustomerID=@CustomerID;" & _   "select CustomerID,ContactName,CompanyName from customers"   cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value _       = lnkRemove.CommandArgument   GridView1.DataSource = GetData(cmd)   GridView1.DataBind()End Sub

 

Based on the sender argument I am getting the reference of the LinkButton that is clicked and with the CommandArgument of the LinkButton I am getting the ID of the record to be deleted. After the delete query I am firing a select query and the rebinding the GridView.

 

Page 20: gridview

Pagination

For pagination I have added the OnPageIndexChanging event on which I am assigning the new page index to the ASP.Net GridView control and then rebinding the data.

        

C#

 protected void OnPaging(object sender, GridViewPageEventArgs e){    BindData();    GridView1.PageIndex = e.NewPageIndex;    GridView1.DataBind();}

 

VB.Net

Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)   BindData()   GridView1.PageIndex = e.NewPageIndex   GridView1.DataBind()End Sub

 

ASP.Net AJAX and JQuery

As you have seen in the start I had added an Update Panel and a DIV along with ASP.Net GridView Control.

Basically the Update Panel will give the asynchronous calls thus not reloading the complete page and the JQuery will block the UI until the update panel is refreshed completely. But instead of blocking the complete page I am blocking only the contents of the DIV dvGrid. To achieve this I am using the JQuery BlockUI Plugin

<script type = "text/javascript" src = "scripts/jquery-1.3.2.min.js"></script><script type = "text/javascript" src = "scripts/jquery.blockUI.js"></script><script type = "text/javascript">    function BlockUI(elementID) {    var prm = Sys.WebForms.PageRequestManager.getInstance();    prm.add_beginRequest(function() {    $("#" + elementID).block({ message: '<table align = "center"><tr><td>' +      '<img src="images/loadingAnim.gif"/></td></tr></table>',     css: {},     overlayCSS: {backgroundColor:'#000000',opacity: 0.6, border:'3px solid #63B2EB'    }    });    });    prm.add_endRequest(function() {

Page 21: gridview

        $("#" + elementID).unblock();    });    }    $(document).ready(function() {             BlockUI("dvGrid");            $.blockUI.defaults.css = {};                });</script> 

That’s all the scripting required and the following is achieved with the above scripts. It will block the Grid until the update panel finishes its work. Refer the figure below

 

That’s it. With this the article comes to an end, hope you liked it I’ll get back soon with a new one. Download the sample in VB.Net and C# using the link below.

Page 22: gridview

How to use GridView with Insert, Edit, Update, Delete the Ado.net way C#

Now, I in this article I will use Itemtemplate and Edittemplate where we will do Edit, Update and Delete the records.

Before to do it first of all create a database.

 

Or

Run the following script in your Sql Server 2005.

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N‘[dbo].[tbuser]‘) AND type in (N‘U’))

BEGIN

CREATE TABLE [dbo].[tbuser](

[id] [int] IDENTITY(1,1) NOT NULL,

[uid] [varchar](50) NOT NULL,

[Name] [varchar](50) NULL,

[address] [varchar](50) NULL,

[salary] [int] NULL,

Page 23: gridview

CONSTRAINT [PK_tbuser] PRIMARY KEY CLUSTERED

(

[uid] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

END

Well place the GridView control on a form and set the following property.

1.AutoGenerateColumns=”False”

And set the Gridview Events name is

onpageindexchanging=”GridView1_PageIndexChanging”

onrowcancelingedit=”GridView1_RowCancelingEdit”

onrowdeleting=”GridView1_RowDeleting” onrowediting=”GridView1_RowEditing”

onrowupdating=”GridView1_RowUpdating”

*Snapshot how to do set Events of GridView select the GridView and press f4

 

Or copy paste the following Source Code

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”user.aspx.cs” Inherits=”user” %>

Page 24: gridview

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head runat=”server”>

<title>Untitled Page</title>

<style type=”text/css”>

.style1

{

width: 100%;

}

.style2

{

}

</style>

</head>

<body>

<form id=”form1″ runat=”server”>

<table class=”style1″>

<tr>

<td class=”style2″>

Uid</td>

<td>

<asp:TextBox ID=”Txt_uid” runat=”server”></asp:TextBox>

</td>

Page 25: gridview

</tr>

<tr>

<td class=”style2″>

Name</td>

<td>

<asp:TextBox ID=”Txt_Name” runat=”server”></asp:TextBox>

</td>

</tr>

<tr>

<td class=”style2″>

Address</td>

<td>

<asp:TextBox ID=”Txt_Address” runat=”server” Height=”22px” >

</asp:TextBox>

</td>

</tr>

<tr>

<td class=”style2″>

Salary</td>

<td>

<asp:TextBox ID=”Txt_Salary” runat=”server”></asp:TextBox>

</td>

</tr>

Page 26: gridview

<tr>

<td class=”style2″>

&nbsp;</td>

<td>

<asp:Button ID=”Button1″ runat=”server” Height=”26px” onclick=”Button1_Click”

Text=”Insert” Width=”89px” />

</td>

</tr>

<tr>

<td class=”style2″>

&nbsp;</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td class=”style2″ colspan=”2″>

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”

CellPadding=”1″ ForeColor=”#333333″ GridLines=”None”

onpageindexchanging=”GridView1_PageIndexChanging”

onrowcancelingedit=”GridView1_RowCancelingEdit”

onrowdeleting=”GridView1_RowDeleting” onrowediting=”GridView1_RowEditing”

onrowupdating=”GridView1_RowUpdating” CellSpacing=”1″>

Page 27: gridview

<RowStyle BackColor=”#EFF3FB” />

<Columns>

<asp:TemplateField HeaderText=”S.No”>

<ItemTemplate>

<%#Container.DataItemIndex +1 %>

<asp:Label ID=”Label5″ runat=”server”></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Uid”>

<ItemTemplate>

<asp:Label ID=”Label1″ runat=”server” Text=’<%# Eval(“uid”) %>‘></asp:Label>

<asp:Label ID=”lb_id” runat=”server” Text=’<%# Eval(“id”) %>‘></asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:Label ID=”lbl_edit” runat=”server” Text=’<%# Eval(“id”) %>‘></asp:Label>

</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Name”>

<ItemTemplate>

<asp:Label ID=”Label2″ runat=”server” Text=’<%# Eval(“Name”) %>‘></asp:Label>

</ItemTemplate>

<EditItemTemplate>

Page 28: gridview

<asp:TextBox ID=”txt_ename” runat=”server” Text=’<%# Eval(“name”) %>‘></asp:TextBox>

</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Salary”>

<ItemTemplate>

<asp:Label ID=”Label3″ runat=”server” Text=’<%# Eval(“Salary”) %>‘></asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID=”txt_esal” runat=”server” Text=’<%# Eval(“Salary”) %>‘></asp:TextBox>

</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Address”>

<ItemTemplate>

<asp:Label ID=”Label4″ runat=”server” Text=’<%# Eval(“Address”) %>‘></asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID=”txt_eadd” runat=”server” Height=”81px”

Text=’<%# Eval(“address”) %>‘

TextMode=”MultiLine” Width=”246px”></asp:TextBox>

</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Edit”>

Page 29: gridview

<ItemTemplate>

<asp:LinkButton ID=”LinkButton1″ runat=”server” CommandName=”edit”>Edit</asp:LinkButton>

</ItemTemplate>

<EditItemTemplate>

<asp:LinkButton ID=”LinkButton2″ runat=”server” CommandName=”update”>Update</asp:LinkButton>

&nbsp;<asp:LinkButton ID=”LinkButton3″ runat=”server” CommandName=”cancel”>Cancel</asp:LinkButton>

</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Delete”>

<ItemTemplate>

<asp:LinkButton ID=”LinkButton4″ runat=”server” CommandName=”delete”

onclientclick=”return confirm(‘Are you sure want to delete the current record ?’)”>Delete</asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

</Columns>

<FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />

<PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />

<SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />

<HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />

Page 30: gridview

<EditRowStyle BackColor=”#FF9999″ />

<AlternatingRowStyle BackColor=”White” />

</asp:GridView>

</td>

</tr>

<tr>

<td class=”style2″>

&nbsp;</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td class=”style2″>

&nbsp;</td>

<td>

&nbsp;</td>

</tr>

</table>

<div>

</div>

</form>

</body>

</html>

Page 31: gridview

 

Snapshots

CODING

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Data.SqlClient;  // add the namespace

 

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

{

Page 32: gridview

SqlConnection con = new SqlConnection(); // for connection

SqlCommand cmd;

DataTable dt;

SqlDataAdapter adp;

protected void Page_Load(object sender, EventArgs e)

{

con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString; //accessing connection name from Web.config

con.Open();

if (con.State == ConnectionState.Closed)

{

con.Open();

}

con.Close();

 

if (IsPostBack == false)

{

grdview(); // calling the grdview function

}

}

private void grdview()

{

if (con.State == ConnectionState.Closed)

Page 33: gridview

{

con.Open();

}

adp = new SqlDataAdapter(“select * from tbuser order by id desc”, con); //fetching the records from table

dt = new DataTable();

adp.Fill(dt);

if (dt.Rows.Count == 0)

{

Response.Write(“No record found”);

}

else

{

GridView1.DataSource = dt;

GridView1.DataBind();

}

con.Close();

}

 

 

 

protected void Button1_Click(object sender, EventArgs e)

{

if (con.State == ConnectionState.Closed)

Page 34: gridview

{

con.Open();

}

adp = new SqlDataAdapter(“Select uid from tbuser where uid=@uid”, con); // will check the uid if exists then display else condition

adp.SelectCommand.Parameters.AddWithValue(“@uid”, Txt_uid.Text);

dt = new DataTable();

adp.Fill(dt);

adp.Dispose();

if (dt.Rows.Count == 0)

{

// will insert the unique record of uid

cmd = new SqlCommand(“insert into tbuser values(@uid,@Name,@Address,@Salary)”, con);

cmd.Parameters.AddWithValue(“@uid”, Txt_uid.Text);

cmd.Parameters.AddWithValue(“@Name”, Txt_Name.Text);

cmd.Parameters.AddWithValue(“@Address”, Txt_Address.Text);

cmd.Parameters.AddWithValue(“@Salary”, Txt_Salary.Text);

cmd.ExecuteNonQuery();

cmd.Dispose();

con.Close();

grdview();

}

else

{

Page 35: gridview

Response.Write(“user name is already exits”);

}}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

GridView1.PageIndex = e.NewPageIndex; // for pageindexing

grdview();

}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

GridView1.EditIndex = -1; // will cancel the updating

grdview();

}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{ //will delete the Record

Label id = ((Label)(GridView1.Rows[e.RowIndex].FindControl(“lb_id”))); // here we will find the label name “lb_id” which is bound with

//field name id

if (con.State == ConnectionState.Closed)

{ con.Open(); }

cmd = new SqlCommand(“delete from  tbuser where id=@id”, con);

cmd.Parameters.AddWithValue(“@id”, id.Text);

cmd.ExecuteNonQuery();

Page 36: gridview

cmd.Dispose();

con.Close();

grdview();

}

 

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

GridView1.EditIndex = e.NewEditIndex;

grdview();

}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

// The label which is in Edittemplate name “lbl_edit” bind with id field from the table

Label id = ((Label)(GridView1.Rows[e.RowIndex].FindControl(“lbl_edit”))) ;

if (con.State == ConnectionState.Closed)

{ con.Open(); }

//In edittemplate where we placed the textbox which were bind with the fields and here we will find the

// controls and will access the fields and update the records

cmd = new SqlCommand(“update tbuser set name=@name,salary=@salary,address=@address where id=@id”, con);

cmd.Parameters.AddWithValue(“@name”, ((TextBox)(GridView1.Rows[e.RowIndex].FindControl(“txt_ename”))).Text);//name

Page 37: gridview

cmd.Parameters.AddWithValue(“@salary”, Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].FindControl(“txt_esal”))).Text));//salary

cmd.Parameters.AddWithValue(“@address”, ((TextBox)(GridView1.Rows[e.RowIndex].FindControl(“txt_eadd”))).Text);//address

cmd.Parameters.AddWithValue(“@id”, id.Text);//id

cmd.ExecuteNonQuery();

cmd.Dispose();

GridView1.EditIndex = -1;

con.Close();

grdview();

}}

ASP.Net GridView- Insert Edit Update and Delete the ADO.NET wayThis demo is a continuation of my previous example “Binding GridView with Data”. If you are not familiar of binding the GridView the ado.net way then I would suggest looking at my previous example first before you proceed reading  this example.

Basically, this demo describes the basic way on how to do INSERT, EDIT, UPDATE  and DELETE data in ASPNET GridView Control using the ADO.NET way. 

STEP 1: Creating a Database Table

In this demo, I presumed that you already have a basic background on how to create a simple database table. In this example, I used my own database called SampleDB which has Customers Table and basically contains the following field columns:

CustomerID – PKCompanyNameContactNameContactTitleAddressCountry STEP 2: Setting Up the Connection String

      <connectionStrings>            <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SampleDB.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>      </connectionStrings>

 

Page 38: gridview

   

          STEP 3: Setting up the GUI

Just for the simplicity of this demo, I set up the GUI like this:

   

    <html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>GridView Data Manipulation</title></head><body>    <form id="form1" runat="server">    <div>        <table cellpadding="0" cellspacing="0">            <tr>                <td style="width: 100px; height: 19px;">                    Company ID</td>                <td style="width: 100px; height: 19px;">                    Company</td>                <td style="width: 100px; height: 19px;">                    Name</td>                <td style="width: 100px; height: 19px;">                    Title</td>                <td style="width: 100px; height: 19px;">                    Address</td>                <td style="width: 100px; height: 19px;">                    Country</td>            </tr>            <tr>                <td style="width: 100px">                    <asp:TextBox ID="TextBox1" runat="server"/></td>                <td style="width: 100px">                    <asp:TextBox ID="TextBox2" runat="server"/></td>                <td style="width: 100px">                    <asp:TextBox ID="TextBox3" runat="server"/></td>                <td style="width: 100px">                    <asp:TextBox ID="TextBox4" runat="server"/></td>                <td style="width: 100px">                    <asp:TextBox ID="TextBox5" runat="server"/></td>                <td style="width: 100px">                    <asp:TextBox ID="TextBox6" runat="server"/></td>                <td style="width: 100px">                    <asp:Button ID="Button1" runat="server" Text="Add New" OnClick="Button1_Click" /></td>            </tr>        </table>                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true">        <Columns>            <asp:BoundField DataField="CustomerID" HeaderText="ID" ReadOnly="true"/>

Page 39: gridview

            <asp:BoundField DataField="CompanyName" HeaderText="Company"/>            <asp:BoundField DataField="ContactName" HeaderText="Name"/>            <asp:BoundField DataField="ContactTitle" HeaderText="Title" />            <asp:BoundField DataField="Address" HeaderText="Address"/>            <asp:BoundField DataField="Country" HeaderText="Country"/>        </Columns>        </asp:GridView>    </div>    </form></body></html>

 

Note:  I have set the CustomerID field to ReadOnly so that the field cannot be edited.

STEP 4: Binding GridView with Data

I will not elaborate on this step because I already describe the details in my previous example about “Binding GridView with Data”. Here are the code blocks for binding the GridView.

public partial class _Default : System.Web.UI.Page {    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            BindGridView();        }    }

     private string GetConnectionString()    {        return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;    }

     #region Bind GridView    private void BindGridView()    {         DataTable dt = new DataTable();        SqlConnection connection = new SqlConnection(GetConnectionString());         try        {            connection.Open();            string sqlStatement = "SELECT Top(10)* FROM Customers";            SqlCommand cmd = new SqlCommand(sqlStatement, connection);            SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);

               sqlDa.Fill(dt);              if (dt.Rows.Count > 0)              {                GridView1.DataSource = dt;                GridView1.DataBind();              }

Page 40: gridview

        }        catch (System.Data.SqlClient.SqlException ex)        {                string msg = "Fetch Error:";                msg += ex.Message;                throw new Exception(msg);        }        finally        {            connection.Close();        }    }    #endregion}

 

Now, we already know how to bind our GridView with data from database. So let’s proceed on adding a new data in GridView.

STEP 5: Adding New Data in GridView

As you have noticed in STEP 2, we have added six TextBox and a Button in the web form in order for us to type the information there and Insert them to the database. Now let’s create a method for executing the Update or Insert.

Here are the code blocks for our Insert and Update method in the code behind:

#region Insert New or Update Record    private void UpdateOrAddNewRecord(string ID, string Company, string Name, string Title, string Address, string Country, bool isUpdate)    {        SqlConnection connection = new SqlConnection(GetConnectionString());        string sqlStatement = string.Empty;

         if (!isUpdate)        {            sqlStatement = "INSERT INTO Customers"+"(CustomerID,CompanyName,ContactName,ContactTitle,Address,Country)" +"VALUES (@CustomerID,@CompanyName,@ContactName,@ContactTitle,@Address,@Country)";        }        else        {            sqlStatement = "UPDATE Customers" +                           "SET CompanyName = @CompanyName,                           ContactName = @ContactName," +                           "ContactTitle = @ContactTitle,Address =                             @Address,Country = @Country" +                           "WHERE CustomerID = @CustomerID,";        }        try        {            connection.Open();            SqlCommand cmd = new SqlCommand(sqlStatement, connection);

Page 41: gridview

            cmd.Parameters.AddWithValue("@CustomerID", ID);            cmd.Parameters.AddWithValue("@CompanyName", Company);            cmd.Parameters.AddWithValue("@ContactName", Name);            cmd.Parameters.AddWithValue("@ContactTitle", Title);            cmd.Parameters.AddWithValue("@Address", Address);            cmd.Parameters.AddWithValue("@Country", Country);            cmd.CommandType = CommandType.Text;            cmd.ExecuteNonQuery();        }        catch (System.Data.SqlClient.SqlException ex)        {            string msg = "Insert/Update Error:";            msg += ex.Message;            throw new Exception(msg);

         }        finally        {            connection.Close();        }    }    #endregion

 

The UpdateOrAddNewRecord is a method that takes seven parameters.  Six of those parameters basically come from the TextBox values that were entered in the page. The last parameter is a boolean value which tells the method whether to execute an Insert (false) or Update (true). Default is true.

Here’s the code block for calling the method UpdateOrAddNewRecord on Button_Click event and pass the corresponding parameters needed:

    protected void Button1_Click(object sender, EventArgs e)    {        UpdateOrAddNewRecord(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text, TextBox6.Text, false);        //Re Bind GridView to reflect changes made        BindGridView();    }

 

As you can see from above, We have called the BindGridView() method again in order to reflect the changes made and display the new added data in the GridView. See output below with red mark.

Click to enlarge the image

Page 42: gridview

STEP 6: Edit and Update Records In GridView

One of the good things about GridView is that it provides a built-in CommandField Buttons which allows us to perform certain actions like editing, updating,deleting and selecting of GridView data.

To add those command fields mentioned in the GridView you can follow these few steps below:1.       Switch to Design View2.       Right Click on the GridView and Select  --> Show Smart Tag --> Add New Columns3.       On the List Select CommandField4.       Check Delete and Edit/Update options then OK

 As you can see the Edit and Delete CommandField are automatically added in the last column of GridView.  Now we can start to write our codes for editing and updating the information in the GridView. In-order to perform Edit and Update in GridView we need to use three events ( GridView_RowEditing, GridView_RowCancelingEdit , GridView_RowUpdating). For those who do not know on how to generate Events in GridView you can follow these steps below: 

1.       Switch to Design View in Visual Studio Designer2.       Click on the GridView3.       Navigate to the GridView Property Pane and then SWITCH to Event Properties 4.       From there you would be able to find the list of events including those three  events mentioned

above5.       Double Click on that to generate the Event handler for you6.       Then write the codes there

 Here’s the code for each events:

Page 43: gridview

              protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e){        GridView1.EditIndex = e.NewEditIndex; // turn to edit mode        BindGridView(); // Rebind GridView to show the data in edit mode}

 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e){        GridView1.EditIndex = -1; //swicth back to default mode        BindGridView(); // Rebind GridView to show the data in default mode}

 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e){        //Accessing Edited values from the GridView        string id = GridView1.Rows[e.RowIndex].Cells[0].Text; //ID        string company = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text; //Company        string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; //Name        string title = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text; //Title        string address = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text; //Address        string country = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text; //Country

         UpdateOrAddNewRecord(id,company,name,title,address,country,true); // call update method        GridView1.EditIndex = -1;        BindGridView(); // Rebind GridView to reflect changes made} 

STEP 7: Perform Delete in GridView Since we are using the Built-in Delete CommandField Button in GridView, we can use the GridView_RowDeleting event to delete specific row in GridView. Here’s the code block for the Delete method:               #region Delete Record    private void DeleteRecord(string ID)    {        SqlConnection connection = new SqlConnection(GetConnectionString());

Page 44: gridview

        string sqlStatement = "DELETE FROM Customers WHERE CustomerID = @CustomerID";        try        {            connection.Open();            SqlCommand cmd = new SqlCommand(sqlStatement, connection);            cmd.Parameters.AddWithValue("@CustomerID", ID);            cmd.CommandType = CommandType.Text;            cmd.ExecuteNonQuery();        }        catch (System.Data.SqlClient.SqlException ex)        {            string msg = "Deletion Error:";            msg += ex.Message;            throw new Exception(msg);

         }        finally        {            connection.Close();        }    }#endregion

 

Here’s the code block for calling the delete method at RowDeleting event

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e){   string id = GridView1.Rows[e.RowIndex].Cells[0].Text; get the id of the selected row   DeleteRecord(id);//call delete method   BindGridView();//rebind grid to reflect changes made}

 

That’s it! Hope you will find this article useful!

How to Select/Insert/Delete/Update records in SQL Server database with VB.NET.

I presume the SQL Server database file D:\myDB.mdf contains a Table named Users which has two fields as below:Field Name    Data Typename            Varchar(20)phone           Varchar(20)

Imports System.Data.SqlClient  

 

Public Class Form1  

 

Page 45: gridview

    ' Shared variables  

    Dim con As SqlConnection = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")  

    Dim cmd As SqlCommand  

    Dim myDA As SqlDataAdapter  

    Dim myDataSet As DataSet  

 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load  

        ShowData()  

    End Sub 

 

    'Binding database table to DataGridView  

    Public Sub ShowData()  

        cmd = New SqlCommand("Select * FROM Users", con)  

        If con.State = ConnectionState.Closed Then con.Open()  

        myDA = New SqlDataAdapter(cmd)  

        myDataSet = New DataSet()  

        myDA.Fill(myDataSet, "MyTable")  

        DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView  

    End Sub 

 

    ' Retrieve/Select records  

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click  

        cmd = New SqlCommand("SELECT * FROM Users Where name='Martin'", con)  

        If con.State = ConnectionState.Closed Then con.Open()  

        Dim sdr As SqlDataReader = cmd.ExecuteReader()  

        While sdr.Read = True 

            MessageBox.Show(sdr.Item("name") & " " & sdr.Item("phone"))  

        End While 

        sdr.Close()  

    End Sub 

 

    ' Insert record  

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click  

        cmd = New SqlCommand("Insert Into Users(name, phone) Values('phenry', ‘88866677’)", con)  

        If con.State = ConnectionState.Closed Then con.Open()  

        cmd.ExecuteNonQuery()  

        ShowData() 'Rebinding to DataGridView and view result  

    End Sub 

 

    ' Update record  

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click  

        cmd = New SqlCommand("Update Users Set phone=’34’ Where name='Martin'", con)  

        If con.State = ConnectionState.Closed Then con.Open()  

        cmd.ExecuteNonQuery()  

        ShowData() 'Rebinding to DataGridView and view result  

    End Sub 

 

    'Delete record  

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click  

        cmd = New SqlCommand("Delete * From Users Where name='Martin'", con)  

        If con.State = ConnectionState.Closed Then con.Open()  

        cmd.ExecuteNonQuery()  

Page 46: gridview

        ShowData() 'Rebinding to DataGridView and view result  

    End Sub 

 

    ' Dispose Database Connection object  

    Private Sub Form4_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed  

        con.Close()  

        con = Nothing 

    End Sub 

 

End Class 

Select, Insert, Update, Delete Using Stored Procedure in SQL Server 2008Here, we will see how to create select, insert, update, delete statements using stored procedure. Let's take a look at a practical example. We create a table.

Creating Table

CREATE TABLE employee(    id          INTEGER NOT NULL PRIMARY KEY,    first_name  VARCHAR(10),    last_name   VARCHAR(10),    salary      DECIMAL(10,2),    city        VARCHAR(20),     )

Now insert some values in the table and using select statement to select a table.

 INSERT INTO employee VALUES (2, 'Monu',  'Rathor',4789,'Agra'); GO INSERT INTO employee VALUES (4, 'Rahul' ,  'Saxena',   5567,'London'); GO INSERT INTO employee VALUES (5, 'prabhat',  'kumar',  4467,'Bombay'); go INSERT INTO employee VALUES (6, 'ramu',  'kksingh',  3456, 'jk'); go select * from employee

Table looks like this.

Page 47: gridview

Figure 1

Stored procedure for Select, insert, update, delete

Here, we create a stored procedure for select,insert,update,delete statements to select the data from the table.

Alter PROCEDURE MasterInsertUpdateDelete(    @id         INTEGER,    @first_name  VARCHAR(10),    @last_name   VARCHAR(10),    @salary      DECIMAL(10,2),    @city        VARCHAR(20),      @StatementType nvarchar(20) = '') ASBEGINIF @StatementType = 'Insert'BEGINinsert into employee (id,first_name,last_name,salary,city) values( @id, @first_name,  @last_name,  @salary, @city)    END  IF @StatementType = 'Select' BEGINselect * from employeeEND   IF @StatementType = 'Update' BEGINUPDATE employee SET            First_name =  @first_name, last_name = @last_name, salary = @salary,            city = @city       WHERE id = @idEND  else IF @StatementType = 'Delete'BEGINDELETE FROM employee WHERE id = @idENDend

Page 48: gridview

Now press F5 to execute the stored procedure.

Now open object explorer and select storeprocedure MasterInsertUpdateDelete.

Stored Procedure to Check Insert

StatementType = 'Insert'

MasterInsertUpdateDelete -> right click select execute stored procedure...

Page 49: gridview

Figure2

Execute procedure window will be open.

Page 50: gridview

Figure3

Now for insert we fill the data in required field.

StatementType=insert

Page 51: gridview

Figure4

Click on the ok Button. and check in the employee table with following inserted data.

Page 52: gridview

Figure5

Stored Procedure to Check update

MasterInsertUpdateDelete -> right click select execute stored procedure...

Execute procedure window will be open.

StatementType = 'Update'

Page 53: gridview

Figure6

Click on the ok Button. and check in the employee table with following updated data where id is 7.

Page 54: gridview

Figure7

Stored Procedure to Check Delete

MasterInsertUpdateDelete -> right click select execute stored procedure...

Execute procedure window will be open.

StatementType = 'Delete'

Figure8

Page 55: gridview

we delete record from table which has id=2

Click on the ok Button. and check in the employee table with following deleted data where id is 2.

C#.Net DataGridView Insert,Update,Select,Delete using Stored procedure

C#.Net DataGridView Insert,Update,Select,Delete using Stored procedure

1.create new winform add one datagrid ,3 label and 3 TextBox2. add 3 button for insert,update,delete3.create stored procedure for allInset query using stored Procedure:

create procedure insertemp1 (@id int,@name varchar(100),@sal int)Asinsert into parthi values(@id,@name,@sal)

Select query using stored Procedure:

Create Procedure insertemp2AsSELECT * FROM parthi

Update query using stored procedure:

create procedure insertemp3 (@id int,@name varchar(100),@sal int)Asupdate parthi set name=@name,salary=@sal where id=(@id)

Delete query using stored procedure:create procedure insertemp4(@id int) asdelete from parthi where id=@id

Page 56: gridview

Form1.cs:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;

namespace gridEdit{public partial class Form1 : Form{

SqlConnection con =new SqlConnection("server =192.168.3.150;uid=sa;pwd=sa@1234;database=nss1");public Form1(){InitializeComponent();}

private void Form1_Load(object sender, EventArgs e){//this.Size = Screen.PrimaryScreen.Bounds.Size;//this.Location = new Point(0, 0);

SqlCommand command = new SqlCommand("insertemp2", con);SqlDataAdapter adapter = new SqlDataAdapter(command);DataSet ds = new DataSet();adapter.Fill(ds, "parthi");this.dataGridView1.DataSource = ds;this.dataGridView1.DataMember = "parthi";

}

private void btninsert_Click(object sender, EventArgs e)

Page 57: gridview

{int txtid =Convert.ToInt32(textBox1.Text);string txtname = textBox2.Text;int txtsal = int.Parse(textBox3.Text);

SqlCommand cmd = new SqlCommand("insertemp1", con);con.Open();cmd.CommandType = CommandType.StoredProcedure;cmd.CommandText = "insertemp1";cmd.Parameters.AddWithValue("@id", txtid);cmd.Parameters.AddWithValue("@name", txtname);cmd.Parameters.AddWithValue("@sal", txtsal);cmd.ExecuteNonQuery();MessageBox.Show("inserted......");con.Close();}

private void button2_Click(object sender, EventArgs e){int txtid = Convert.ToInt32(textBox1.Text);string txtname = textBox2.Text;int txtsal = int.Parse(textBox3.Text);

SqlCommand cmd = new SqlCommand("insertemp3", con);con.Open();cmd.CommandType = CommandType.StoredProcedure;cmd.CommandText = "insertemp3";cmd.Parameters.AddWithValue("@id", txtid);cmd.Parameters.AddWithValue("@name", txtname);cmd.Parameters.AddWithValue("@sal", txtsal);cmd.ExecuteNonQuery();MessageBox.Show("updated......");con.Close();}

private void button3_Click(object sender, EventArgs e){int txtid = Convert.ToInt32(textBox1.Text);SqlCommand cmd = new SqlCommand("insertemp4", con);con.Open();cmd.CommandType = CommandType.StoredProcedure;

Page 58: gridview

cmd.CommandText = "insertemp4";cmd.Parameters.AddWithValue("@id", txtid);cmd.ExecuteNonQuery();MessageBox.Show("deleted......");con.Close();}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e){int i;i = dataGridView1.SelectedCells[0].RowIndex;textBox1.Text = dataGridView1.Rows[i].Cells[0].Value.ToString();textBox2.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();textBox3.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();

}

}------

How to Insert, Edit, Update and Delete Data with DataGridView in Windows Form C#.net ||Inserting , Updating and Deleting with DataGridView in Windows forms C#.net

Labels: C#.net, GridView, Windows Applications

In this article I am showing to Inserting , Editing , Updating and Deleting options with DataGridview.For that I am Designing form with two textboxes with Name and Location ,DataGridview to display data and four buttons to Save , Edit , Update and Delete.To do this just follow below steps:

         In form load I am binding the data from database.         In save button click event saving data to database which are inserted into the name and location

textboxes.         In Delete button click event Deleting the selected row data in DataGridview from database.         In Edit button Click event filling the selected data from Gridview into Name and location

textboxes.         In Update Button click event updating data which are edited the name and location textboxes.

Write the following code in Form.cs :

Page 59: gridview

Form.cs Code :

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Configuration;using System.Data.SqlClient;

namespace savedata{    public partial class Form1 : Form    {

        SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["Sqlcon"].ConnectionString);        public Form1()        {            InitializeComponent();            Bind();

        }

        private void Clear()        {            txtName.Text = string.Empty;            txtLocation.Text = string.Empty;        }

        private void btnSave_Click(object sender, EventArgs e)        {            con.Open();            SqlCommand cmd = new SqlCommand("Insert Into Test_Data(Name,Location) Values (@Name,@Location)", con);            cmd.Parameters.AddWithValue("Name", txtName.Text);            cmd.Parameters.AddWithValue("Location", txtLocation.Text);            cmd.ExecuteNonQuery();            con.Close();            MessageBox.Show("Inserted sucessfully");            Bind();            Clear();        }

Page 60: gridview

        private void Bind()        {            con.Open();            SqlDataAdapter da = new SqlDataAdapter("select * from Test_Data", con);            DataTable dt = new DataTable();            da.Fill(dt);            dataGridView1.DataSource = dt;            con.Close();        }

        private void btnDelete_Click(object sender, EventArgs e)        {            SqlCommand delcmd = new SqlCommand();            if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)            {                delcmd.CommandText = "DELETE FROM Test_Data WHERE ID=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";                con.Open();                delcmd.Connection = con;                delcmd.ExecuteNonQuery();                con.Close();                dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);                MessageBox.Show("Row Deleted");            }            Bind();        }

        private void btnUpdate_Click(object sender, EventArgs e)        {            con.Open();            SqlCommand cmd = new SqlCommand("Update Test_Data set Name=@Name,Location=@Location Where(Name=@Name)", con);            cmd.Parameters.AddWithValue("@Name", txtName.Text);            cmd.Parameters.AddWithValue("@Location", txtLocation.Text);            cmd.ExecuteNonQuery();            MessageBox.Show("updated......");            con.Close();            Bind();            Clear();        }

        private void btnEdit_Click_1(object sender, EventArgs e)        {            int i;

Page 61: gridview

            i = dataGridView1.SelectedCells[0].RowIndex;            txtName.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();            txtLocation.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();        }    }}

Then run the application you will get output like below: