Tuesday, June 1, 2010

Passing value and auto refresh parent window from popup

Here I will show how to pass value from popup window to parent window and refresh parent window while closing popup. This is a common task and often asked in asp.net forum. In this example, I have taken two forms:

Default4.aspx >Its Master page is  MasterPage.master (This is parent page)
Default5.aspx (This is child page)

I have taken UpdatePanel in parent page to check whether it is working properly with UpdatePanel. Let us see codes of Default4.aspx:

HTML:


<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
    CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">

    <script type="text/javascript">
        function OpenPopup() {
            window.open("Default5.aspx", "Popup", "scrollbars=no,resizable=no,width=500,height=250");
            return false;
        }
    script>

asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <div>
                    <table width="80%">
                        <tr>
                            <td>
                                <asp:Label ID="Label1" runat="server" Text="Value from popup:">asp:Label>
                            td>
                            <td>
                                <asp:TextBox ID="txtOpenner" runat="server">asp:TextBox>
                                 <asp:Button ID="Button1" runat="server" Text="Popup" OnClientClick="OpenPopup()" />
                                <asp:Label ID="Label2" runat="server" Text="">asp:Label>
                            td>
                        tr>
                    table>
                div>
            ContentTemplate>
        asp:UpdatePanel>
    div>
asp:Content>

Design preview: 


When user click on Popup button popup window will be displayed and the textbox will show value sent from popup window.

Code behind:


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

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int count = 0;
        if (!IsPostBack)
        {
            Session["Count"] = 0;
        }
        if (IsPostBack)
        {
            Session["Count"] = count = int.Parse(Session["Count"].ToString())+1;
            Label2.Text = "This page is postedback " + count.ToString() + " times";
        }
    }
}


Here I am counting how many time PostBack event is occurring in parent page and showing in Label2. I am doing this to clearly understand that parent page is refreshed clearly.



Now, Let us see codes of Default5.aspx:

HTML:



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

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>title>

    <script language="javascript" type="text/javascript">

        function SendValue() {
            var val = document.getElementById('<%=TextBox1.ClientID%>').value;
            window.opener.document.getElementById("ctl00_ContentPlaceHolder1_txtOpenner").value = val;
            window.close();
            window.opener.document.forms(0).submit();
        }

    script>

head>
<body>
    <form id="form1" runat="server">
    <div>
        <table width="100%">
            <tr>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="Give your name here:">asp:Label>
                td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
                     <asp:Button ID="btnSend" runat="server" Text="Send to opener" OnClientClick="SendValue()" />
                td>
            tr>
        table>
    div>
    form>
body>
html>

Code behind:



using System;

public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Earn money from Freelancer.com:

Freelance Jobs

Tuesday, May 25, 2010

Show client side alert message from server side code even when update panel is used



Developers might want to display client side message with information from server side to their users when they have completed some execution at server side. People may try in different way for this purpose.
For example:
Response.Write() method with JavaScript code inside the method:

string mes = "Hello Dhaka";
        Response.Write("<script language=\"javascript\"  type=\"text/javascript\">alert('" + mes + "');</script>");

or ClientScript.RegisterStartupScript() method:

string message = "<script language=\"javascript\"  type=\"text/javascript\">alert('Hello Dhaka');</script>";
        if (!ClientScript.IsStartupScriptRegistered("mes"))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "mes", message);
        }

But these code doesn't work when you use update panel in your page. So better solution is to use ScriptManager.RegisterStartupScript() method. This works whether update panel is used or not. So let's see the code snippet below:

string message = string.IsNullOrEmpty(TextBox1.Text) ? "Please give a text to textbox." : "You have given: " + TextBox1.Text.Trim();
        string script = "<script language=\"javascript\"  type=\"text/javascript\">alert('" + message + "');</script>";
        ScriptManager.RegisterStartupScript(Page, this.GetType(), "AlertMessage", script, false);

With this code snippet you can display a modal message that their data was saved or updated successfully or not.

Saturday, May 22, 2010

Truncate table when referenced by a FOREIGN KEY

If you try to truncate a table that is referenced by foreign key you usually get the following error:

Cannot truncate table 'TableName' because it is being referenced by a FOREIGN KEY constraint.

To avoid this error the easiest way to use DELETE without where clause and RESEED the identity:

DELETE FROM AccVoucher
DBCC CHECKIDENT (AccVoucher, RESEED, 0)

Sunday, May 9, 2010

Highlight gridview row on mouse hover in asp.net

Gridview control is a customizable and flexible control used to display data in tabular format. It has some nice features. But lacks of some client side features that makes web users happy. We can easily add these features with few lines of code.

For example, a common task is to highlight gridview row on mouse over which is not provided with gridview control. Here we will see how easily we can do the task.

In order to change gridview row color we need to add/remove style attributes to that specific row using JavaScript onmouseover and onmouseout client event. We can do it on RowDataBound or RowCreated gridview event.

Code Snippet:


protected void gvHrEmploye_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
            {

                // when mouse is over the row, save original color to new attribute, and change it to highlight color
                e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#EEFFAA'");

                // when mouse leaves the row, change the bg color to its original value  
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");


            }
        }

or,



protected void gvHrEmploye_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
            {

                // when mouse is over the row, save original color to new attribute, and change it to highlight color
                e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#EEFFAA'");

                // when mouse leaves the row, change the bg color to its original value  
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");


            }
        }

It works properly even if you set AlternatingRowStyle property or the row is previously selected.

How it works:







Monday, February 1, 2010

Export gridview data to excel and word


Every software has a common requirement to export data to Microsoft Excel or Word format. I saw multiple on this topic in asp.net forum.  Here I will explain a simple way of exporting your gridview data to excel (.xls) or word (.doc) format when used with master page and updatepanel.  
Firstly we will write html codes:



<table style="width: 100%;">
                                    <tr>
                                        <td>
                                            <asp:Label ID="Label3" runat="server" Text="Export to: "></asp:Label>
                                            <asp:LinkButton ID="lnkExportToExcel" runat="server"
                                                OnClick="lnkExportToExcel_Click">Excel</asp:LinkButton>
                                            &nbsp;<asp:LinkButton ID="lnkExportToWord" runat="server"
                                                onclick="lnkExportToWord_Click">Word</asp:LinkButton>
                                            &nbsp;<asp:DropDownList ID="ddlExportOption" runat="server">
                                                <asp:ListItem Value="0">This Page</asp:ListItem>
                                                <asp:ListItem Value="1">All Page</asp:ListItem>
                                            </asp:DropDownList>
                                            &nbsp;</td>
                                    </tr>
                                </table>
Code behind:
Now we will write lnkExportToExcel and lnkExportToWord click event handler code:
protected void lnkExportToExcel_Click(object sender, EventArgs e)
        {
            if (ddlExportOption.SelectedIndex == 0)
            {
                Helper.Export("excel", gvHrEmploye, this.Page);
            }
            else
            {
                int pageNo = gvHrEmploye.PageIndex;
                gvHrEmploye.AllowPaging = false;
                BindList();
                Helper.Export("excel", gvHrEmploye, this.Page);
                gvHrEmploye.AllowPaging = true;
                gvHrEmploye.PageIndex = pageNo;
                BindList();
            }
        }

protected void lnkExportToWord_Click(object sender, EventArgs e)
        {
            if (ddlExportOption.SelectedIndex == 0)
            {
                Helper.Export("word", gvHrEmploye, this.Page);
            }
            else
            {
                int pageNo = gvHrEmploye.PageIndex;
                gvHrEmploye.AllowPaging = false;
                BindList();
                Helper.Export("word", gvHrEmploye, this.Page);
                gvHrEmploye.AllowPaging = true;
                gvHrEmploye.PageIndex = pageNo;
                BindList();
            }
        }


Here notice that we are currently displaying data or all data based on users choice.


Then we will look at export method which actually does the job:
public static void Export(string type, GridView gv, Page page)
    {
        if (type == "excel")
        {
            page.Response.AddHeader("content-disposition", "attachment;filename=EmployeeList.xls");
            page.Response.ContentType = "application/vnd.xls";
        }
        else if (type == "word")
        {
            page.Response.AddHeader("content-disposition", "attachment;filename=EmployeeList.doc");
            page.Response.ContentType = "application/msword";
        }
        page.Response.Charset = String.Empty;
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
        gv.RenderControl(hw);
        page.Response.Write(sw.ToString());
        page.Response.End();
    }
You can use this code to export gridview data to excel and word format. This method works fine when working with pages that does not have update panel and have no master page. But when used with master page and update panel it gives an error while executing RenderControl()method.
Error:
"Control of type GridView must be placed inside form tag with runat = server"
To solve this error you have to override VerifyRenderingInServerForm method:
public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }
This method confirms that HtmlForm control is rendered for specified ASP.Net server control at runtime.
If you run this time you will get another error:
RegisterForEventValidation can only be called during Render()


To solve this problem add EnableEventValidation = "false" page tag of .aspx page.
<%@ Page Language="C#" MasterPageFile="~/Master/MasterPage.master" AutoEventWireup="true"
    MaintainScrollPositionOnPostback="true" CodeFile="HrEmployeeForm.aspx.cs" Inherits="ERP.Web.UI.HrEmployeeForm"
    EnableEventValidation="false" %>


This time your code should work properly. Have a nice feature working properly in your asp.net application. Thanks.