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.

Alert(“Message”) box in Asp.Net Codebehind and Call java fuction from codebehind

In highly interactive websites and intranet sites, you probably want to let the users know what’s going on when they delete, save, export etc. on the site. Those kinds of status messages are widely used and are often implemented by a JavaScript alert box on the web page. You can call Alert.Show(“Message”) from Asp.Net Codebehind.

On button click, alert box display values in textbox1.
Here is code:

protected void Button1_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + TextBox1.Text.Replace("'","\\'")  + "');</script>");
}

Another way, You can just call javascript from codebehind.

<head runat="server">
    <title>Ashish's Blog</title>
    <script type="text/javascript">
    function callAlert(msg)
    {
        alert(msg);
    }
    </script>
 </head>

Codebehind code:

protected void Button1_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "Message", "callAlert('" + TextBox1.Text.Replace("'","\\'")  + "');",true);
}

If your content page is wrapped in an ASP.NET AJAX UpdatePanel, then you cannot use the ClientScript.RegisterStartupScript to call a JavaScript function during a partial-page postback. Instead, use the ScriptManager.RegisterStartupScript() method.

    protected void Button1_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + TextBox1.Text.Replace("'","\\'")  + "');</script>", false);
     }

Thanks.

Nested GridView in Show/Hide effect using C#.Net

This article explains how to make an ASP.NET nested GridView. There may be many ways to do this, but here is my code.



First, put gridview1 into asp design page then put another gridview2 inside previous gridview.
Here is code file

<form id="form1" runat="server">
<asp:GridView ID="GridView1"
runat="server"
DataKeyNames="CustomerID" AutoGenerateColumns="false"
OnRowDataBound="gv_RowDataBound" Width="80%"
AllowPaging="True" PageSize="20" >
<HeaderStyle CssClass="dataTable" />
<RowStyle CssClass="dataTable" />
<AlternatingRowStyle CssClass="dataTableAlt" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:switchViews('div<%# Eval("CustomerID") %>', 'one');">
<img id="imgdiv<%# Eval("CustomerID") %>" alt="Click to show/hide orders" border="0" src="Images/expand_button.png" />
</a>
</ItemTemplate>
<AlternatingItemTemplate>
<a href="javascript:switchViews('div<%# Eval("CustomerID") %>', 'alt');">
<img id="imgdiv<%# Eval("CustomerID") %>" alt="Click to show/hide orders" border="0" src="Images/expand_button.png" />
</a>
</AlternatingItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" HtmlEncode="False" />
<asp:BoundField DataField="Name" HeaderText="Name" HtmlEncode="False" />
<asp:BoundField DataField="Address" HeaderText="Address" HtmlEncode="False" />
<asp:TemplateField>
<ItemTemplate>
</td></tr>
<tr>
<td colspan="100%" >
<div id="div<%# Eval("CustomerID") %>" style="display:none;position:relative;left:25px;" >
<asp:GridView ID="GridView2" runat="server" Width="80%"
AutoGenerateColumns="false" DataKeyNames="ItemCode"
EmptyDataText="No orders for this customer." >
<HeaderStyle CssClass="dataTable" />
<AlternatingRowStyle CssClass="dataTableAlt" />
<RowStyle CssClass="dataTable" />
<Columns>
<asp:BoundField DataField="OrderDate" HeaderText="Order Date" HtmlEncode="False" />
<asp:BoundField DataField="ShippedDate" HeaderText="ShippedDate" HtmlEncode="False" />
<asp:BoundField DataField="ShipTO" HeaderText="Ship TO" />

</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>

In above code, To get nested gridview effect I simply injected some HTML to end the current row and create a new row. The nested GridView is then placed inside a < DIV> tag where the display of that < DIV> is controled by Javascript. Each < DIV> is assigned a unique ID that corresponds to the main GridView’s rowID and that is passed to the javascript to control the opening and closing of the nested GridView.

Second, In Codebehind file I put datasource of gridview. In order to bind the child GridView2, we can’t use the static DataSource control. We will have to dynamically prepare the query based on the customer ID of the corresponding parent row, and that we can do it in the RowDataBound event of the parent grid as below:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataSource dbSrc= new SqlDataSource();
dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString2"].ConnectionString;
dbSrc.SelectCommand = "SELECT CustomerID, Name, Address FROM Customer";
GridView1.DataSource = dbSrc;
GridView1.DataBind();
}
}
//The code to populate the nested GridView that is called on the main GridView's OnRowDataBound event
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

GridView gv = (GridView)e.Row.FindControl("GridView2");
SqlDataSource dbSrc = new SqlDataSource();
dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString2"].ConnectionString;
dbSrc.SelectCommand = "SELECT OrderDate,ShippedDate, ShipTO FROM Orders where customerID='" + ((DataRowView)e.Row.DataItem)["CustomerID"].ToString() + "'";
gv.DataSource = dbSrc;
gv.DataBind();
}
}

Finally, put JavaScript to show/hide Child gridview ..

<script type="text/javascript">
function switchViews(obj, row) {
var div = document.getElementById(obj);
var img = document.getElementById('img' + obj);

if (div.style.display == "none") {
div.style.display = "inline";
img.src = "images/expand_button_down.png";
} else {
div.style.display = "none";
img.src = "images/expand_button.png";
}
}
</script>

Here is css file for design purpose.

<style type="text/css">
.dataTable
{
text-align:left;
font-size:10pt;
font-family:Verdana, Sans-Serif;
border:solid 1px rgb(210,210,210);
color:gray;

}
.dataTable CAPTION
{
color:Black;
text-align:left;
font-size:12pt;
font-weight:bold;
padding-bottom:5px;
padding-top:15px;
}
.dataTable TH
{
text-decoration:none;
background-color:rgb(210,210,210);
font-family:Tahoma, Sans-Serif, Arial;
font-size:11pt;
font-weight:normal;
color:Black;
border:solid 0px;
padding:2px 4px 2px 2px;
}
.dataTable TD
{
padding-left:6px;
border:solid 0px;
min-width:100px;
}
.dataTable TR
{
border:solid 0px;

}
.dataTableAlt TD
{
font-size: 10pt;
color:rgb(75,75,75);
font-family:Verdana;
border: solid 0px;
padding:2px 0px 2px 8px;
background-color:rgb(245,245,245);
min-width:100px;
}
.dataTableRow
{
color:rgb(75,75,75);
font-family:Verdana;
padding:2px 0px 2px 8px;
border:solid 0px;
background-color:White;
}
.dataTable A:Link, .dataTable A:Visited
{
text-decoration:none;
color:black;
}
.dataTable A:Hover
{
color:Red;
text-decoration:none;
}
</style>

Thanks.

Detecting Refresh or Postback in ASP.NET

One of the biggest challenges for web developers is the resubmission of form data or the refresh of a form to post information to a database. This happens when the user, for whatever reason, resubmits or refreshes the form, which has the potential to cause chaos with duplicated database insertions or repeated email submissions.
In this article I Will show you how to define page is postback or refresh after postback.
Here my simple code

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["PostID"] = "1001";
            ViewState["PostID"] = Session["PostID"].ToString();
            Response.Write("First Load");
        }
        else
        {
            if (ViewState["PostID"].ToString() == Session["PostID"].ToString())
            {
                
                Session["PostID"] = (Convert.ToInt16(Session["PostID"]) + 1).ToString();

                ViewState["PostID"] = Session["PostID"].ToString();
                Response.Write("Postback");

            }
            else
            {
                ViewState["PostID"] = Session["PostID"].ToString();
                Response.Write("refreshed");

            }
        }
    }

Thanks