Edit Gridview Using jQuery Dialog ASP.Net C#

In this article, I’ll explain how to Edit records in ASP.Net GridView control using jQuery Dialog UI. There is many other way to do that but here is the easiest way to do it.

Database:
For this tutorial, I am using Employee database.

CREATE TABLE [dbo].[T_Employees](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](20) NULL,
	[LastName] [nvarchar](20) NULL,
	[Department] [nvarchar](40) NULL,
	[Location] [nvarchar](40) NULL
) ON [PRIMARY]
Insert INTO [dbo].[T_Employees] values ('Tanvi','Patel',' Physiotherapy ','Sydney') 
Insert INTO [dbo].[T_Employees] values ('Ashish','Patel','IT','Sydney')    
Insert INTO [dbo].[T_Employees] values ('Vaishu','Patel','Micro','Sydney')  
Insert INTO [dbo].[T_Employees] values ('Bhavik','Patel',' pediatrician ','Sydney')

Connection string:
Below is the connection string to connect to the database.

<connectionStrings>
    <add name="TempConnectionString" connectionString="Data Source=ASHISH;Initial Catalog=Temp;Persist Security Info=True;User ID=sa;Password=********" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Aspx Page:
In this tutorial, there are two aspx pages.

1. Default.aspx — To implement Gridview control
2. EditEmployee.aspx –To Edit Employee

Default.aspx page:
Below HTML Markup of the page 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 brnRefreah that will be used to refresh after Edit the records in the GridView Control.

        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
        </asp:ScriptManager>
         <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
        <img src="Loading.gif" alt="" />
        </ProgressTemplate>
        </asp:UpdateProgress>

    <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional" >
   <ContentTemplate>
       
       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
            DataSourceID="SqlDataSource1">
            <Columns>
            <asp:TemplateField HeaderText="ID">
           <ItemTemplate >
               <a id="popup" href='EditEmployee.aspx?id=<%# Eval("ID") %>' >edit</a>
         </ItemTemplate>
           </asp:TemplateField>
              <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" 
                    ReadOnly="True" SortExpression="ID" />
               
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                    SortExpression="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" 
                    SortExpression="LastName" />
                <asp:BoundField DataField="Department" HeaderText="Department" 
                    SortExpression="Department" />
                <asp:BoundField DataField="Location" HeaderText="Location" 
                    SortExpression="Location" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:TempConnectionString %>" 
            SelectCommand="SELECT Top 10 * FROM [T_Employees]"></asp:SqlDataSource>

           <asp:Button ID="btnRefresh" Text="refresh" runat="server" 
            onclick="btnRefresh_Click" />
   </ContentTemplate>
</asp:UpdatePanel>

You notice that in gridview I have placed Edit link (line 17 in above code) to pass ID of Employee to EditEmployee page. (For example. ‘editEmployee.aspx?id=1).
Now when user click on Edit link, Dialog box will display and load EditEmployee.aspx page. To create dialog box on click event of Edit link we are going to use jQuery Dialog UI. Here is code

 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/jquery-ui.min.js"></script>
    <link type="text/css" rel="Stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/themes/smoothness/jquery-ui.css">
    <script type="text/javascript">
        $(document).ready(function () {
            $('a#popup').live('click', function (e) {
                
                var page = $(this).attr("href")  //get url of link
              
                var $dialog = $('<div></div>')
                .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
                .dialog({
                    autoOpen: false,
                    modal: true,
                    height: 450,
                    width: 'auto',
                    title: "Edit Employee",
                    buttons: {
                        "Close": function () { $dialog.dialog('close'); }
                                },
                    close: function (event, ui) {
                        
                       __doPostBack('<%= btnRefresh.ClientID %>', '');  // To refresh gridview when user close dialog
                    }
                });
                $dialog.dialog('open');
                e.preventDefault();
            });
        });
    </script>

In dialog Close event, I use __doPostBack(‘<%= btnRefresh.ClientID %>‘, ”); to refresh Gridview. This code fire btnRefresh_click event thats why we need to place gridview1.databind() in it to refresh gridview.
Codebehide (Default.aspx.cs):

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        GridView1.DataBind();
    }
}

EditEmployee.aspx Page:
In this page, we get Employee ID from Querystring. After getting Employee ID We use sql connection to get FirstName, LastName, Location and Department from Database.

EditEmployee.aspx

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <h3>Edit Employee</h3>
        <asp:Label ID="lblResult" runat="server" ForeColor="Green"></asp:Label>
        <asp:Panel ID="pnlEdit" runat="server">
        
    <p>ID:<asp:TextBox ID="txtID" ReadOnly="true" runat="server"></asp:TextBox></p>
    <p> FirstName: <asp:TextBox ID="txtfName"  runat="server"></asp:TextBox></p>
    <p> LastName:<asp:TextBox ID="txtlNmae"  runat="server"></asp:TextBox></p>
    <p>Department: <asp:TextBox ID="txtDept"  runat="server"></asp:TextBox></p>
    <p>Location:<asp:TextBox ID="txtLocation"  runat="server"></asp:TextBox></p>
<p> <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
    </p>
    </asp:Panel>
    </ContentTemplate>
    </asp:UpdatePanel>
    </form>

Codebehind code: EditEmployee.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class EditPopup : System.Web.UI.Page
{
    string CT = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string EID = Request.QueryString["id"];
            
            using (SqlConnection cn = new SqlConnection(CT))
            {
                string query = "Select * from T_Employees where ID='" + EID + "'";
                using (SqlCommand cmd = new SqlCommand(query, cn))
                {
                    cn.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    if(dr.Read() )
                    {
                        txtID.Text = EID;
                        txtfName.Text = dr["FirstName"].ToString();
                        txtlNmae.Text = dr["LastName"].ToString();
                        txtDept.Text = dr["Department"].ToString();
                        txtLocation.Text = dr["Location"].ToString();
                    }
                    cn.Close();
                    cn.Dispose();

                }
            }
        }
           
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ///save Employee Recoed code
        ///

        using (SqlConnection cn = new SqlConnection(CT))
        {
            string query = "Update T_Employees  Set FirstName='"+txtfName.Text+"', LastName='"+txtlNmae.Text +"', Department='"+txtDept.Text +"', Location='"+txtLocation.Text +"' where ID='" + txtID.Text  + "'";
            using (SqlCommand cmd = new SqlCommand(query, cn))
            {
                cn.Open();
                cmd.ExecuteNonQuery();
                
                cn.Close();
                cn.Dispose();
                lblResult.Text = "Employee Data Saved!!";
                pnlEdit.Visible = false;
            }
        }
        
    }
}

CSS File to style Gridview:

th {
font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #4f6b72;
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
border-top: 1px solid #C1DAD7;
letter-spacing: 2px;
text-transform: uppercase;
text-align: left;
padding: 6px 6px 6px 6px;
background: #D5EDEF;
}
 
td {
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
background: #fff;
padding: 6px 6px 6px 6px;
color: #4f6b72;
}
 
td.alt
{
background: #F5FAFA;
color: #797268;
}
 
td.boldtd
{
font: bold 13px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
background: #D5EDEF;
color: #797268;
}

Download

[wpdm_file id=3]

Thanks.

Convert nvarchar to float or number in sql

I recently came across the following usefull SQL query, Maybe you’ll find it useful.
In SQL, convert nvarchar (string) to number can be achieve by using cast and convert SQL function.
For example, I have Following table

You may notice that UnitPrice has nvarchar datatype.
Here is my Query to convert UnitPrice datatype to float

SELECT [Name]
      ,[Description]
      ,[Unit]
      ,convert(float,[UnitPrice]) [UnitPrice]
      ,[CreateDate]
  FROM [Product]

Result:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.

Reason: Have a close look at the table, iMac UnitPrice is 1,200.00. UnitPrice 1,200.00 have coma which stop sql to convert into float.
Final Query:

SELECT [Name]
      ,[Description]
      ,[Unit]
      ,convert(float,replace([UnitPrice],',','') )[UnitPrice]
      ,[CreateDate]
  FROM [Product]

Thanks

Redirection from iframe in asp.net or javascript

In this tutorial we will learn how to perform redirection from IFrame in asp.net.
For example, I has a webpage that contains the form containing two textboxes and one asp:button. When click on button it redirects the user to another page but problem was that the next page was being opened inside the iframe rather than in parent window because the webpage that containing the form was also in iframe.

Solution 1
Here we using the server side onClick event of asp:button to redirecting user to another page and client side OnClientClick event to open new page in parent window. NewWindow() JavaScript code that we have written in the OnClientClick event of asp:button will take care that user must be redirected to next page within parent window rather than IFrame.

Code: (iFrame)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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>Ashish Blog</title>
    <script type="text/javascript">
        function NewWindow() {
            document.forms[0].target = "_top";
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Ashish&amp;amp;#39;s Blog<br />
        UserName:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        Password:<asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="NewWindow();" onclick="Button1_Click"  />
    </div>
    </form>
</body>
</html>
 protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }

Solution 2:

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'Default.aspx';}", true);  
    }

Note:- In case if this code is not working properly in IE9 then you have to give the absolute path of targeting webpage such as

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'http://ashishblog.com/Default.aspx';}", true);  
    }

Currency Exchange Rate in webpage using C# ASP.NET

NOTE: GOOGLE turn off currency API but now you can https://www.google.com/finance/converter?a=1&from=AUD&to=INR

Some time ago I found the following Google API , which provides the currency conversion rates for free. Maybe you’ll find it useful.
In this article, I’ll explain how to get currency rate in ASP.Net using C#.

For example, 1 AUD = ? INR (1 Australian Dollar = ? Indian Rupee )
To get INR from 1 AUD, we need to call google API in following format: ( you can try by paste this url into your web browse)

http://www.google.com/ig/calculator?hl=en&q=1AUD%3D%3FINR
The number 1 before AUD is the amount of dollars or quantity.

Above Url returns a JSON object with the details.:

{lhs: "1 Australian dollar",rhs: "47.8167309 Indian rupees",error: "",icc: true}

As you can see the result is called rhs, but it combines the resulting value with the text “Indian rupees”. Now we will remove the string and store the result as a decimal.

We implement fuction called Convert with three parameter (amount, fromCurrency, toCurrency) which return Exchange rate in decimal.

Code:

public static decimal Convert(decimal amount, string fromCurrency, string toCurrency)
        {
            WebClient web = new WebClient();
 
            string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
 
            string response = web.DownloadString(url);
 
            Regex regex = new Regex("rhs: \\\\\\"(\\\\d*.\\\\d*)");
            Match match = regex.Match(response);
 
            decimal rate = System.Convert.ToDecimal(match.Groups[1].Value);
 
            return rate;
        }

Thanks