26

ASP.NET Open PopUp Window Update Refresh Values

This example explains how to Open PopUp Window In Asp.Net And Update Refresh Parent Child Values using ClientScript And RegisterStartupScript.
I am opening popup window from aspx page and updating values in parent window from child or popup window using javascript and ClientScript.RegisterStartupScript.

Open PopUp Window In Asp.Net
I have added to labels in Default.aspx page and one button to open popup window.

I've also added a PopUp.aspx page which is having two textboxes and a button to update lable values of parent page.

The textboxes in popup window are populated with Text values of lables in parent page (Default.aspx), after making changes in textbox values i'm updating values back in parent page.

HTML source Parent page
<form id="form1" runat="server">
<div>
First Name :
<asp:Label ID="lblFirstName" runat="server" Text="amiT">
</asp:Label><br />
 <br />
Last Name:&nbsp;
<asp:Label ID="lblLastName" runat="server" Text="jaiN">
</asp:Label><br />
<br />
<asp:Button ID="btnPop" runat="server" Text="Click To Edit Values" />
</div>
</form>


Write following JavaScript in Head section of page.
   1:  <script type="text/javascript">
   2:  function openPopUp()
   3:  {
   4:   var popUrl = 'PopUp.aspx?fn=' + document.getElementById('<%= lblFirstName.ClientID %>').innerHTML + '&ln=' + document.getElementById('<%= lblLastName.ClientID %>').innerHTML;
   5:   var name = 'popUp';
   6:   var appearence ='dependent=yes,menubar=no,resizable=no,'+
   7:                   'status=no,toolbar=no,titlebar=no,' +
   8:                   'left=5,top=280,width=230px,height=140px';
   9:  var openWindow = window.open(popUrl, name, appearence);
  10:  openWindow.focus();
  11:  }
  12:  </script>


In this i m getting values of lables and passing them to popuup page as querystrings

Write this code in Page_Load event of Default.aspx (parent) page
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
 string updateValuesScript = 
@"function updateValues(popupValues)
{
 document.getElementById('lblFirstName').innerHTML=popupValues[0];
 document.getElementById('lblLastName').innerHTML=popupValues[1];
}";
        
this.ClientScript.RegisterStartupScript(Page.GetType(), 
"UpdateValues", updateValuesScript.ToString(), true);
btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')");
}

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim updateValuesScript As String = "function updateValues(popupValues)" & vbCr & vbLf & "{" & vbCr & vbLf & " document.getElementById('lblFirstName').innerHTML=popupValues[0];" & vbCr & vbLf & " document.getElementById('lblLastName').innerHTML=popupValues[1];" & vbCr & vbLf & "}"
    
    Me.ClientScript.RegisterStartupScript(Page.[GetType](), "UpdateValues", updateValuesScript.ToString(), True)
    btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')")
End Sub

HTML SOURCE OF PopUp.aspx(child) page

<form id="form1" runat="server">
<div>
First Name :
<asp:TextBox ID="txtPopFName" runat="server" Width="113px">
</asp:TextBox><br />
<br />
Last Name:<asp:TextBox ID="txtPopLName" runat="server" 
                       Width="109px">
</asp:TextBox><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" 
            Text="Button" /></div>
</form>


C# CODE PopUp.aspx
protected void Page_Load(object sender, EventArgs e)
{
 string updateParentScript = 
 @"function updateParentWindow()
 {                                                                               
   var fName=document.getElementById('txtPopFName').value;     
   var lName=document.getElementById('txtPopLName').value;   
   var arrayValues= new Array(fName,lName);
   window.opener.updateValues(arrayValues);       
   window.close(); 
 }";
 this.ClientScript.RegisterStartupScript(this.GetType(), 
     "UpdateParentWindow", updateParentScript, true);
 if (!IsPostBack)
 {
   txtPopFName.Text = Request["fn"];
   txtPopLName.Text = Request["ln"];
 }
   Button1.Attributes.Add("onclick", "updateParentWindow()");
}

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim updateParentScript As String = "function updateParentWindow()" & vbCr & vbLf & " {                                                                               " & vbCr & vbLf & "   var fName=document.getElementById('txtPopFName').value;     " & vbCr & vbLf & "   var lName=document.getElementById('txtPopLName').value;   " & vbCr & vbLf & "   var arrayValues= new Array(fName,lName);" & vbCr & vbLf & "   window.opener.updateValues(arrayValues);       " & vbCr & vbLf & "   window.close(); " & vbCr & vbLf & " }"
    Me.ClientScript.RegisterStartupScript(Me.[GetType](), "UpdateParentWindow", updateParentScript, True)
    If Not IsPostBack Then
        txtPopFName.Text = Request("fn")
        txtPopLName.Text = Request("ln")
    End If
    Button1.Attributes.Add("onclick", "updateParentWindow()")
End Sub

Hope this helps

Download sample code attached



26

AutoCompleteExtender TextBox CompletionList Width Ajax ASP.NET

Set AutoCompleteExtender TextBox CompletionList Width And Style With CSS Ajax ASP.NET. In this example i am setting Width of Completion List in Ajax AutoComplete Extender TextBox.

The default behavior of completion list takes width equal to the width of textbox. we can change this behavior by applying some CSS style to set the width we want. default width is as shown below in the Image.

 AutoCompleteExtender TextBox CompletionList Width And Style With CSS
I have also explained how to implement AutoComplete Extender TextBox In EditItemTemplate Of GridView

I have also created example to Add Progress Image in Ajax AutoComplete TextBox




In AutoComplete Extender default width of completion list is equals to the width of textbox, to fix this issue write the CSS script mentioned below in Head section of html source of page
<head runat="server">
    <title>Progress Image in AutoComplete TextBox</title>
<style>
        .AutoExtender
        {
            font-family: Verdana, Helvetica, sans-serif;
            font-size: .8em;
            font-weight: normal;
            border: solid 1px #006699;
            line-height: 20px;
            padding: 10px;
            background-color: White;
            margin-left:10px;
        }
        .AutoExtenderList
        {
            border-bottom: dotted 1px #006699;
            cursor: pointer;
            color: Maroon;
        }
        .AutoExtenderHighlight
        {
            color: White;
            background-color: #006699;
            cursor: pointer;
        }
        #divwidth
        {
          width: 150px !important;    
        }
        #divwidth div
       {
        width: 150px !important;   
       }
 </style>
</head>
The code in bold is setting the width of completion list, you can change the dimensions according to your needs.

Now Put a div with id "divwidth" above the html source of autocomplete extender
<div ID="divwidth"></div>

and add this line in autocomplete extender HTML source

CompletionListElementID="divwidth"

The complete html source of AutoComplete Extender will look like
<asp:TextBox ID="txtAutoComplete" runat="server" Width="252px">
</asp:TextBox>   
<div ID="divwidth"></div>
<ajaxToolkit:AutoCompleteExtender runat="server" 
             ID="AutoComplete1"
             BehaviorID="autoComplete"
             TargetControlID="txtAutoComplete"
             ServicePath="AutoComplete.asmx" 
             ServiceMethod="GetCompletionList"
             MinimumPrefixLength="1" 
             CompletionInterval="10"
             EnableCaching="true"
             CompletionSetCount="12"
             CompletionListCssClass="AutoExtender"
             CompletionListItemCssClass="AutoExtenderList"
             CompletionListHighlightedItemCssClass
             ="AutoExtenderHighlight"
             CompletionListElementID="divwidth">
<ajaxToolkit:AutoCompleteExtender>

And this is how the AutoComplete TextBox will look like
AutoComplete List Width CSS style


Hope this helps


24

Detect Page Refresh In ASP.NET

This post explains how to Detect Page Refresh In ASP.NET 2.0,3.5,4.0 Using C# And VB.NET. If you have created a aspx page and have put a button on it, And in Click event of this button if you are inserting some data in database, after click if user refresh the page than click event gets fired again resulting data insertion to database again.

To stop events on the page getting fired on browser refresh we need to write bit of code to avoid it

In this example i've put a Label and a Button on the page, on click the label Text becomes Hello and when i refresh the page label's text again becomes Hello.

HTML SOURCE OF PAGE


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

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label><br />
<br />
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click"
Text="Button" /></div>
</form>
</body>
</html>

In Page_Load event i m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event i am creating a Viewstate variable and assigning Session variable's value to it
Than in button's click event i am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed
C# Code Bihind
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}

}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() ==
ViewState["CheckRefresh"].ToString())
{
Label1.Text = "Hello";
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "Page Refreshed";
}
}

protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
}


Download the Sample Code



24

Pass Send GridView Row Value/Data Using Hyperlink In ASP.NET

In this example i am describing how to Pass Transfer Or Send GridView Row Data Values To Other asp.net page using hyperlink.

Pass Transfer Send GridView Row Data Values With Hyperlink
I've put a hyperlink column in gridview to pass values through querystring, and using request.querystring on the second page to retrieve values.

You would also like to read
LinkButton in GridView and QueryString in ASP.NET to pass data


We need to set DataNavigateUrlFields and DataNavigateUrlFormatString properties of hyperlink in gridview to pass the row data 
HTML markup of the page


<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="ID,Name,Location" 
DataNavigateUrlFormatString=
"Default2.aspx?id={0}&name={1}&loc={2}" 
Text="Transfer values to other page" />
<asp:BoundField DataField="ID" HeaderText="ID" 
                SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" 
                SortExpression="Name" />
<asp:BoundField DataField="Location" HeaderText="Location" 
                SortExpression="Location" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]">
</asp:SqlDataSource>

Now write code mentioned below to retrieve values on Default2.aspx page
C# code behind
protected void Page_Load(object sender, EventArgs e)
    {
        string strID = Request.QueryString["id"];
        string strName = Request.QueryString["name"];
        string strLocation = Request.QueryString["loc"];
        lblID.Text = strID;
        lblName.Text = strName;
        lblLocation.Text = strLocation;
    }
VB.NET code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim strID As String = Request.QueryString("id")
    Dim strName As String = Request.QueryString("name")
    Dim strLocation As String = Request.QueryString("loc")
    lblID.Text = strID
    lblName.Text = strName
    lblLocation.Text = strLocation
End Sub

Hope this helps


Find More Articles