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

Scrollable GridView with Fixed Headers using jQuery Plugin

Using the same example I have created a jQuery Plugin for Scrollable GridView with Fixed header so that you can directly make a GridView scrollable.   HTML Markup < form   id ="form1"   runat ="server"> < asp : GridView   ID ="GridView1"   runat ="server"   AutoGenerateColumns   =   "false"> < Columns > < asp : BoundField   DataField   =   "ContactName"   HeaderText   =   "Contact Name"   /> < asp : BoundField   DataField   =   "City"   HeaderText   =   "City"   /> < asp : BoundField   DataField   =   "Country"   HeaderText   =   "Country"   /> Columns > asp : GridView > form >   Applying the Scrollable Grid jQuery Plugin < script   src ="Scripts/jquery-1.4.1.min.js"   type ="text/javascript"> script > < script   src ="Scripts/Scro...

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...

ADO.NET Concepts With example

COMMAND OBJECT  Command object is the biggest object in ADO.NET  It is the only object which can perform actions with database  It  can be created directly using Command class or can be created using Connection.Create command (factory classes also contain creation of Command). Ex:  SqlConnection sqlCon = new SqlConnection("......");    SqlCommand sqlCmd = sqlCon.CreateCommand();  Commands that we run depend upon the kind of query that we want to execute with database. All databases support two types of queries. i. Action Queries ii. Non-action Queries Action queries are those which change the state of database and which don‟t return any query results(though they return the number of records affected). Ex: Insert, Delete and Update statements Non-action queries are those which don‟t affect the database but return the results to the user. Ex: Select statement Method of execution of queries: Command object provides the following methods to execute queries: 1. Ex...