Skip to main content

Add Edit Update Records in GridView using Modal Popup in ASP.Net


Add Edit Update Records in GridView using Modal Popup in ASP.Net

In this article, I’ll explain how to Add and Edit records in ASP.Net GridView control using ASP.Net AJAX Control Toolkit Modal Popup Extender.
Database
For this tutorial, I am using Microsoft’s NorthWind database. You can download it using the following link.
Connection string
Below is the connection string to connect to the database.
<connectionStrings>
    <addname="conString"
    connectionString="Data Source=.\SQLExpress;database=Northwind;
    Integrated Security=true"/>
</connectionStrings>
 
HTML Markup
Below is the HTML Markup of the page. Below you will notice that I have placed a Script Manager and an ASP.Net Update Panel on the page. Inside the Update Panel I have placed an ASP.Net GridView Control along with a Modal Popup Extender that will be used to Add or Edit the records in the GridView Control.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" AlternatingRowStyle-BackColor = "#C2D69B" 
HeaderStyle-BackColor = "green" AllowPaging ="true"
OnPageIndexChanging = "OnPaging"
PageSize = "10" >
<Columns>
<asp:BoundField DataField = "CustomerID" HeaderText = "Customer ID" HtmlEncode = "true" />
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" HtmlEncode = "true" />
<asp:BoundField DataField = "CompanyName" HeaderText = "Company Name" HtmlEncode = "true"/>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "CustomerID">
   <ItemTemplate>
       <asp:LinkButton ID="lnkEdit" runat="server" Text = "Edit" OnClick = "Edit"></asp:LinkButton>
   </ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick = "Add" />
 
<asp:Panel ID="pnlAddEdit" runat="server" CssClass="modalPopup" style = "display:none">
<asp:Label Font-Bold = "true" ID = "Label4" runat = "server" Text = "Customer Details" ></asp:Label>
<br />
<table align = "center">
<tr>
<td>
<asp:Label ID = "Label1" runat = "server" Text = "CustomerId" ></asp:Label>
</td>
<td>
<asp:TextBox ID="txtCustomerID" Width = "40px" MaxLength = "5" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID = "Label2" runat = "server" Text = "Contact Name" ></asp:Label>
</td>
<td>
<asp:TextBox ID="txtContactName" runat="server"></asp:TextBox>   
</td>
</tr>
<tr>
<td>
<asp:Label ID = "Label3" runat = "server" Text = "Company" ></asp:Label>
</td>
<td>
<asp:TextBox ID="txtCompany" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick = "Save" />
</td>
<td>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClientClick = "return Hidepopup()"/>
</td>
</tr>
</table>
</asp:Panel>
<asp:LinkButton ID="lnkFake" runat="server"></asp:LinkButton>
<cc1:ModalPopupExtender ID="popup" runat="server" DropShadow="false"
PopupControlID="pnlAddEdit" TargetControlID = "lnkFake"
BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
<asp:AsyncPostBackTrigger ControlID = "btnSave" />
</Triggers>
</asp:UpdatePanel>
 
Binding the GridView
The code snippet provided below is used to bind the GridView Control. It simply fires a select query on the Customers table of the NorthWind Database.
C#
private String strConnString =ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindData();
    }
}
 
private void BindData()
{
    string strQuery = "select CustomerID,ContactName,CompanyName" +
                       " from customers";
    SqlCommand cmd = new SqlCommand(strQuery);
    GridView1.DataSource = GetData(cmd);
    GridView1.DataBind();
}
 
private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            return dt;
        }
    }
}
 
VB.Net
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
 
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Me.BindData()
        End If
End Sub
 
Private Sub BindData()
        Dim strQuery As String = ("select CustomerID,ContactName,CompanyName" + " from customers")
        Dim cmd As SqlCommand = New SqlCommand(strQuery)
        GridView1.DataSource = GetData(cmd)
        GridView1.DataBind()
End Sub
 
Private Function GetData(ByVal cmd As SqlCommand) As DataTable
        Dim dt As DataTable = New DataTable
        Dim con As SqlConnection = New SqlConnection(strConnString)
        Dim sda As SqlDataAdapter = New SqlDataAdapter
        cmd.Connection = con
        con.Open()
        sda.SelectCommand = cmd
        sda.Fill(dt)
        Return dt
End Function
 
Add Functionality
On click of the add button the following method is called up, which simply sets the textboxes empty and displays the modal popup by calling the AJAX ModalPopupExtender.
C#
protected void Add(object sender, EventArgs e)
{
    txtCustomerID.ReadOnly = false;
    txtCustomerID.Text = string.Empty;
    txtContactName.Text = string.Empty;
    txtCompany.Text = string.Empty;
    popup.Show();
}
 
VB.Net
Protected Sub Add(ByVal sender As ObjectByVal e As EventArgs)
        txtCustomerID.ReadOnly = False
        txtCustomerID.Text = String.Empty
        txtContactName.Text = String.Empty
        txtCompany.Text = String.Empty
        popup.Show()
End Sub
 
Screenshot
The screenshot below displays the modal popup shown to the user when the Add button is clicked.

Add Records To GridView Using Modal Popup

Edit Functionality
On click of the Edit button in the GridView row the following method gets called up which simply fills the textboxes with respective values.
C#
protected void Edit(object sender, EventArgs e)
{
    using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
    {
        txtCustomerID.ReadOnly = true;
        txtCustomerID.Text = row.Cells[0].Text;
        txtContactName.Text = row.Cells[1].Text;
        txtCompany.Text = row.Cells[2].Text;           
        popup.Show();
    }
}
 
VB.Net
Protected Sub Edit(ByVal sender As ObjectByVal e As EventArgs)
        Dim row As GridViewRow = CType(CType(sender, LinkButton).Parent.Parent, GridViewRow)
        txtCustomerID.ReadOnly = True
        txtCustomerID.Text = row.Cells(0).Text
        txtContactName.Text = row.Cells(1).Text
        txtCompany.Text = row.Cells(2).Text
        popup.Show()
End Sub
 
Screenshot
The screenshot below displays the modal popup being shown to the user when the Edit Button is clicked.

Edit Records in GridView Using ModalPopup Extender ASP.Net

Updating the records
The following method gets called up when the Save button the modal popup is clicked. The following method simply calls the stored procedure AddUpdateCustomer (described later).
C#
protected void Save(object sender, EventArgs e)
{
    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "AddUpdateCustomer";
        cmd.Parameters.AddWithValue("@CustomerID", txtCustomerID.Text);
        cmd.Parameters.AddWithValue("@ContactName", txtContactName.Text);
        cmd.Parameters.AddWithValue("@CompanyName", txtCompany.Text);
        GridView1.DataSource = this.GetData(cmd);
        GridView1.DataBind();
    }
}
 
VB.Net
Protected Sub Save(ByVal sender As ObjectByVal e As EventArgs)
        Dim cmd As SqlCommand = New SqlCommand
        cmd.CommandType = CommandType.StoredProcedure
        cmd.CommandText = "AddUpdateCustomer"
        cmd.Parameters.AddWithValue("@CustomerID", txtCustomerID.Text)
        cmd.Parameters.AddWithValue("@ContactName", txtContactName.Text)
        cmd.Parameters.AddWithValue("@CompanyName", txtCompany.Text)
        GridView1.DataSource = Me.GetData(cmd)
        GridView1.DataBind()
End Sub
 
The following stored procedure is used to Add and Update the records in the database. The stored procedure first checks if the record exists in the table. If the record exists then the table is simply updated else a new record is inserted in the database.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[AddUpdateCustomer]
      @CustomerID NCHAR(5),
      @ContactName NVARCHAR(30),
      @CompanyName NVARCHAR(40)
AS
BEGIN
      SET NOCOUNT ON;
    IF EXISTS(SELECT * FROM Customers WHERE CustomerID = @CustomerID)
    BEGIN
            UPDATE [Customers]
            SET [CompanyName] = @CompanyName
               ,[ContactName] = @ContactName
            WHERE CustomerID = @CustomerID
    END
    ELSE
    BEGIN
            INSERT INTO [Customers]
           ([CustomerID]
           ,[CompanyName]
           ,[ContactName])
        VALUES
           (@CustomerID
           ,@CompanyName
           ,@ContactName)
    END
   
    SELECT [CustomerID]
          ,[CompanyName]
          ,[ContactName]
      FROM Customers         
END
 
Screenshot
The screenshot below describes the data being saved into the database table. You will notice that a progress bar is being displayed until the data is updated in the database. This helps to block the user from doing multiple clicks. Below is the client side script that will help you achieve the same.

Progress Image While Records Updated To database and GridView Using Modal Popup

<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery.blockUI.js" type="text/javascript"></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
                }
            });
        });
        prm.add_endRequest(function() {
            $("#" + elementID).unblock();
        });
    }
    $(document).ready(function() {
 
        BlockUI("<%=pnlAddEdit.ClientID %>");
        $.blockUI.defaults.css = {};
    });
    function Hidepopup() {
        $find("popup").hide();
        return false;
    }
</script>
 
This completes the article. You can download the related source code ion VB.Net and C# using the link below.
GridViewAddEditRecordsusingModalPopup.zip

Comments

Popular posts from this blog

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {     ...

Hierarchical GridView in ASP.NET with AJAX, JQuery implementation - Part 1

Previously I had blogged some post related to showing two grids in hierarchical way. For example - when I need to show an invoice reports on the screen, the user requesting to show the list of invoices at initial time and they can drill down the details of item details of each invoice by clicking on respective row. The implementations can be in multiple ways, but I had blogged the implementation with AJAX and without AJAX using Java script on ASP.NET page. Below are the URLs of the same – Hierarchical GridView in ASP.NET Hierarchical GridView in ASP.NET with AJAX, Javascript implementation In this post I am taking the same requirements done before and enhance with some additional functionality as per readers expectations. The requirement on this implementation will be – The page should show a Grid View with list of Orders with Expand icon on the first column. On click of expand icon on each row, the Order Details of the Order must be fetched from the database ...

Scrollable Gridview With fixheader using JQuery in Asp.net

Scrollable Gridview With fixheader using JQuery in Asp.net Introduction: In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery.  Description:  In Previous posts I explained lot of articles regarding Gridview. Now I will explain how to implement scrollable gridview with fixed header in asp.net. I have one gridview that contains lot of records and I used  paging for gridview  but the requirement is to display all the records without paging. I removed paging at that time gridview occupied lot of space because it contains more records to solve this problem we implemented scrollbar.  After scrollbar implementation if we scroll the gridview we are unable to see Gridview header.   To implement Scrollable gridview with fixed header I tried to implement concept with css and JavaScript but there is no luck because maintaining fixed header working in IE but not in Mozilla and vice versa to ...