Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, August 11, 2011

Frequent question on parent and child page refresh, reload, function call in asp-net using javascript

There are ways to call client functions in a parent asp.net web page from the child window. This is very helpful in many ways:
1. You can refresh parent page after some updates from child pager
2. You can partially change parts of the parent page
3. You can control the behaviour of parent page from its child (even from iframe child page)

Example? See the way you edit a section in your blogger blog site. When you are logged in and browsing your blog, blogger lets you edit sections of your blog page directly from the public page of your blog. When you click the edit icon, a window will pop up and load with the setting of the editable section. Now when you save your changes the pop up window will close itself and the parent page (your public page) will be refreshed. Want to implement the same?

You can follow these steps:
1. Program your parent page to open new window : You can place a hyperlink in your parent page. There are other several ways to open new window in asp.net web page.
2. Call client function in parent page : Now you can call client function in parent page from the child page. I have already posted how to call javascript function in parent web page from child page.
3. Sometimes your child page is a page loaded in iframe from your parent page. In that case it will be a bit different than what I have mentioned in (2). Learn how to refresh parent parent from iframe child page.

I hope this will help tackle the mostly asked questions on parent and child page programming in asp.net using javascript.

Happy programming!
kick it on DotNetKicks.com

Tuesday, July 19, 2011

Refresh parent page partially from iframe without reloading the iframe using javascript in asp.net

Last time we talked about Refreshing the parent page from child window in asp.net using javascript. This technique is useful in many scenarios. (If you haven't been through How to open new window in asp.net using javscript and C-sharp, I would like to suggest to read the post thoroughly. After this you will clearly see why the stuff we are talking about in this post is important.) But programmers using iframe to load another asp.net web page may wonder if we could only partially refresh the parent page so that iframe keeps itself from reloading. This can by done by calling the parent page javascript function from the child page loaded in the iframe. This way we can even avoid the need of ajax to refresh the parent page without affecting the iframe content. As usual I have presented the simple practical approach to tell you as much clearly as possible - follow please. And before continuing, I would like to inform that there is a post regarding Frequent question on parent and child page refresh, reload, function call in asp-net using javascript that discusses, in aggregate, about some more approaches of parent and child page operations.
Parent Asp.net Page
I am the parent page.
Page to be loaded in parent page iframe
I am content of iframe page.
Visualize the output
Image: refresh parent page partially from iframe without reloading the iframe using javascript in asp.net
What's in the code?
You see a button in the child page that is loaded in the iframe of parent page. On click of the button, the javascript function displayMessageFromIframeChild() of the parent page is called. This function displays the string message from child page in a div of the parent page. That's all. Happy programming!
kick it on DotNetKicks.com

Thursday, July 14, 2011

Refresh parent page from child window using javascript in asp.net web application

Much often we open child windows from parent web page. In the child page we perform some activities, and later close the window. At the very time we may need to refresh the parent page so that changes made in the child window be reflected in the parent window. We can easily accomplish this using javascript in asp.net web page. Let me show the way using code snippets. If it is your iframe page, you still can refresh the parent page partially from page in iframe (because this will avoid reloading the iframe itself), which I have discussed in another post. And right before following, I would like to inform that there is a post regarding Frequent question on parent and child page refresh, reload, function call in asp-net using javascript that discusses, in aggregate, about some more approaches of parent and child page operations.

Parent asp.net web page
Open child window
This is the parent page. Clicking the link will open the child page Child.aspx in a new window. If you wish you can Open the new window in asp.net web page in different ways, which I have already discussed in a previous post.

Child asp.net web page

This is the child page.

protected void btnOk_Click(object sender, EventArgs e)
    { 
        //Implement Your logic here.....
        //..............................
        //now refresh parent page and close this window
        string script = "this.window.opener.location=this.window.opener.location;this.window.close();";
        if (!ClientScript.IsClientScriptBlockRegistered("REFRESH_PARENT"))
            ClientScript.RegisterClientScriptBlock(typeof(string), "REFRESH_PARENT", script, true);        
    }
In the child page, I have just put a button. When the button is clicked, the page logic will be implemented (which I have indicated by the comment lines in the event handler of the button in the asp.net child page).

The asp.net plus javascript logic
I have just created the javascript stuff that refreshes the parent page of this child page; see the lines:
this.window.opener.location=this.window.opener.location;this.window.close();
This line replaces the url of the parent page with its own url - that causes the parent page to reload. And yes, I have registered the javascript code block with ClientScript so that it is executed when the postback life cycle of this child page completes.

Happy programming!
kick it on DotNetKicks.com

Wednesday, December 2, 2009

Prevent page postback on enter key press in textbox in asp-net web page

In an asp.net web page, you may have experienced that pressing enter key postbacks the page. For example, take the following scenario:

<table>

<tr>

<td>Name</td>

<td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>

</tr>

<tr>

<td>Email</td>

<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>

</tr>

<tr>

<td colspan="2">

<asp:Button ID="btnOK" runat="server" Text="OK" />

</td>

</tr>

</table>

In the page, if you press enter key in any of the textboxes, the page will postback, which is not desired.

1.0 What’s the reason?
Lets look at the html markup generated for the page:

The asp.net button control has been rendered with “submit” type, which is the reason of page postback when enter key is pressed in any of the textboxes. Note the following line in the image above:

<input id="btnOK" type="submit" value="OK" name="btnOK"/>

2.0 The Way Out
We can use two different approaches to prevent postback on enter key-press in any of the textboxes:

1. Using UseSubmitBehavior="false" in the asp.net button control’s markup
We can set UseSubmitBehavior="false" in the button markup:

<table>

<tr>

<td>Name</td>

<td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>

</tr>

<tr>

<td>Email</td>

<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>

</tr>

<tr>

<td colspan="2">

<asp:Button ID="btnOK" runat="server" Text="OK" UseSubmitBehavior="false" />

</td>

</tr>

</table>

This stops rendering the button as type=”submit”. Now the rendered markup for the button will be:

Not the following line in the image above as captured from firebug:

<input id="btnOK" type="button" onclick="javascript:__doPostBack('btnOK','')" value="OK" name="btnOK"/>
This shows that there is no more type="submit" attribute, rather onclick="javascript:__doPostBack('btnOK','') has been added.

So you have successfully stopped the page postback now!

2. Prevent enter key press in all the textboxes
One another way to stop the page postback is to prevent enter key press in any of the textboxes. We can use jquery to easily perform the task. This way:

<script type="text/javascript">

$(function(){

$(':text').bind('keydown',function(e){ //on keydown for all textboxes

if(e.keyCode==13) //if this is enter key

e.preventDefault();

});

});

</script>

On page load, all the textboxes in the form are bound to the keydown event to a function. In the function we check if the key pressed in the ‘enter key’. If so, we prevent the further bubbling of the event. Hence it prevents the page postback.

Note: You will need to reference the latest jquery file in the page to use the second technique.

3.0 Conclusion
We looked at two ways to prevent page postback on enter-key press in a textbox in asp.net web page. Both the techniques work well. But I would prefer the first one since this would save the extra client side manipulations in the user’s machine.

4.0 Looking towards hearing from you!
You are warmly welcome to share your experiences. You can start discussion by adding comments from the form below. You can help spreading out the words by bookmarking this article to any of your favourite bookmarking site!

Happy Programming!

kick it on DotNetKicks.com

Friday, July 3, 2009

How to change second textbox text when the first textbox date of AJAX CalendarExtender changes?

Sometime ago I saw an interesting question in asp.net forum. It raised my enthusiasm. I started to code the requirement. And I found one. Here goes the requirement:

Hi!

I have two text boxes inside my aspx page: a) the "txt1" and b) the "txt2". Both text boxes have CalendarExtender controls attached:
a) the txt1 has the "CalendarExtender1"
b) the txt2 has the"CalendarExtender2".

All I want is this:
Using client-side script (or other method without postbacks), I want when the user chooses a date from CalendarExtender1, the same date plus a day front to go to the txt2.

For example:
If the user chooses 03/28/2009 in the CalendarExtender1, I want the value of the txt2 to be the 03/29/2009....
Also, if the month reaches the end, I want the txt2 to take the new moth.

For example:
If the user chooses 03/31/2009 in the CalendarExtender1, I want the value of the txt2 to be the 04/01/2009....

That behavior I want to exists only to the CalendarExtender1 like I describe it. I don't want the user to be able to do this with CalendarExtender2 (the CalendarExtender2 has the default behavior)...

How can I accomplish that? Thank you very much!

There are two solutions provided to this requirement. Let me put them here.

Solution1: (By Kinjalin)

Here you have to add it in Javascript.

<cc1:CalendarExtender ID="ClExFromDt"                     runat="server"                     TargetControlID="TxtFromDate"                     PopupButtonID="BtnFromCal"                     Format="dd/MM/yyyy"                     OnClientDateSelectionChanged="AddDate"                     CssClass="calExt_Theme1"></cc1:CalendarExtender>

Here on OnBlur, write a Javascript function addDate

on Page_Load write the line " Text1.Attributes.Add("onblur", "javascript:addDate();")

& in Javascript Fetch the Value using document.getElementByID("TextBox1").value

add it using below Javascript & bit of ur Logic

//create the date
var myDate = new Date();


//add a day to the date
myDate.setDate(myDate.getDate() + 1);


//add a week
myDate.setDate(myDate.getDate() + 7);

After adding Show it in your TextBox2

$get(TextBox2).value = myDate

Thats it.

Solution2: (By sangam100)

Hi MinimalTech ,

Here goes the prototype, which is close to what kinjalin posted:

Add this script in the design page:

<script>

function addDays() {

dateParts = document.getElementById('txtDate1').value.split('/');

year = dateParts[2];

month = parseInt(dateParts[0])-1;

day = parseInt(dateParts[1]) + 1;



newDate = new Date ( year, month, day );

year = newDate.getYear();

month = newDate.getMonth()+1;

day = newDate.getDate();

formattedDate = month + '/' + day + '/' + year;



document.getElementById('txtDate2').value=formattedDate;

}

</script>

Now in the design page:

Date1:<asp:TextBox ID="txtDate1" runat="server"></asp:TextBox>  Date2 (One day forward):<asp:TextBox ID="txtDate2" runat="server"></asp:TextBox><cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate1" PopupButtonID="txtDate1"></cc1:CalendarExtender>

In the code behind.

txtDate1.Attributes.Add("onchange", "addDays();");

Now this works.

Hope this will be useful to all. Happy Programming!

Friday, May 29, 2009

Check uncheck all rows of gridview (select or deselect all rows at once)

The asp.net gridview data control offers lots of features, that we all know. Adding some cool effects may make this control more usable. For instance, we could check or uncheck all the checkboxes in a column of the gridview control. A column [leftmost column usually] consisting of checkbox control is generally used to select a row. Sometimes we may need to check (and uncheck) all the rows of the gridview. Purpose of doing so may be different depending upon the business requirement. And if we need to do so, we can!


Fig. Check Uncheck all rows in a gridview


Let's be quick to implement check/uncheck all the rows of gridview at once in asp.net gridview. Let's have the markup for the gridview first.

<asp:GridView ID="gvTest" Width="100%" runat="server" AutoGenerateColumns="false">

<Columns>

<asp:TemplateField HeaderText="Select" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center">

<HeaderTemplate >

<input id="chkAll" onclick="javascript:SelectDeselectAllCheckboxes(this);"

runat="server" type="checkbox" />

</HeaderTemplate>

<ItemTemplate>

<asp:CheckBox ID="chkSelect" runat="server" />

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField HeaderText="Name" DataField="Name" ItemStyle-Width="100" />

<asp:BoundField HeaderText="Address" DataField="Address" />

</Columns>

</asp:GridView>

Watched the checkbox control in the header template of the first column? We will use this checkbox to select or deselect all the rows in the gridview. Also mark that clicking this checkbox will call the javascript function SelectDeselectAllCheckboxes. Now is the time to define some javascript snippets to get help from.

<script type="text/javascript">  

function SelectDeselectAllCheckboxes(spanChk){

// Added as ASPX uses SPAN for checkbox



var oItem = spanChk.children;

var theBox= (spanChk.type=="checkbox") ? spanChk : spanChk.children.item[0];

xState=theBox.checked;

elm=theBox.form.elements;

for(i=0;i<elm.length;i++)

if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)

{

//elm[i].click();

if(elm[i].checked!=xState)

elm[i].click();

//elm[i].checked=xState;

}

}

</script>

The task done by the javascript function is simple. It takes the checkbox itself as the input. If it is checked, it searches for all the checkboxes in the gridview and checks them. And reversely, if it is unchecked, all those checkboxes will be consequently unchecked.

There is no need of any codebehind just for this functionality. So I am leaving other parts including databinding code. In fact, for most of the test purposes I do Create DataTable Programmatically and bind the gridview, formview or detailsview to that DataTable.

The only drawback with this technique is that it treats all the checkboxes in or outside the gridview control equal.

You can post your comment, rate this post or add this post to your favourites or share it. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Friday, May 22, 2009

Click the button on keypress in asp.net TextBox

In this post, I am explaining the button click functionality on key press in a textbox. I am using javascript to link the input textbox and the associated button that has to be clicked when the enter key is pressed in the textbox. One can preview it by taking the example of search textbox and GO button!


Fig. Clicking asp.net button on enter key press in textbox

We have seen search textboxes in almost all of the websites which imply 'Go' or 'Search' button click when Return key (Enter key) is pressed. Naturally, users love to press enter key instead of clicking search button next to the input textbox. Wouldn't it be nice if we could do the same for our web pages also? Yeah, I have implemented the button click feature on keypress in textbox control many times. But the last time practice on a web application that added both the textbox and the search button dynamically via javascript was really interesting story that inspired me to re-share the code [since I also learnt it on Internet].

Design Page Markup (SearchPage.aspx)
We do have one textbox and one button in the search page.

<div>

Search Text: <asp:TextBox ID="txtSearchBox" runat="server"></asp:TextBox>

<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />

</div>

JavaScript Code    
This javascript code will be invoked when enter key is pressed in the textbox.

<script>

function clickButton(e, buttonid){

var evt = e ? e : window.event;

var bt = document.getElementById(buttonid);

if (bt){

if (evt.keyCode == 13){

bt.click();

return false;

}

}

}

</script>

We put this javascript code snippet within the head section of the design page.

Code Behind (SearchPage.aspx.cs)

//page load event handler
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//add attribute on the search textbox
//so that when enter key is pressed in the textbox,
//the search button will be fired
txtSearchBox.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearch.ClientID + "')");
}
}

//when search button is clicked
protected void btnSearch_Click(object sender, EventArgs e)
{
//my function to perform search
}


Here we add the onkeypress attribute to the textbox. When a key is pressed, the keycode will be passed to the javascript function. The javascript function checks if this is the enter key, and it is enter key then the button click is invoked by the javascript code.

So far we implemented button click on enter key press from an asp.net web control. To add a little user interactivity in the search textbox, you can implement google search like watermark effect in the search textbox. If you further want to prevent multiple postback, you can just disable asp.net button after first click and enable after postback completes.

Don't forget to expose your views via comment box beneath this post. You can freely share this post! Happy Programming!

Shout it kick it on DotNetKicks.com 

Wednesday, March 11, 2009

Watermark Asp.NET Textbox Using JavaScript

Noticed the watermark implemented in custom google search TextBox, like one in the right side of this page (under heading Search asp.net, C#, oracle, SQL Server related tips and solutions)? I am showing the simple and meaningful watermark implementation of a textbox in asp.net web page in this tipsticle (tips + article).

Truly saying, every time I come across a web page, I do naturally look for the searching textbox in the website. And I do usually find it in the left corner or the right upper corner of the website. Not all the search textboxes implement the watermark but they may initialize the text in the search textbox like your search text here or just search. And my enthusiasm always inspires me to click once and then just click out the textbox to see if watermark has been implemented. In my opinion, it is good to implement watermark for the sake of user-interactivity of a website. (And let me praise facebook homepage for this!)

Ok, lets start out with a search textbox in an asp.net web page.


Now we add a javascript code snippet in the page.



function WatermarkFocus(txtElem, strWatermark) {
if (txtElem.value == strWatermark) txtElem.value = '';
}
function WatermarkBlur(txtElem, strWatermark) {
if (txtElem.value == '') txtElem.value = strWatermark;
}

Now is the time to add onblur and onfocus properties to the asp.net TextBox, referencing the relevant javascript function.

string strWatermarkSearch = "Search";
txtSimpleSearch.Text = strWatermarkSearch;
txtSimpleSearch.Attributes.Add("onfocus", "WatermarkFocus(this, '" + strWatermarkSearch + "');");
txtSimpleSearch.Attributes.Add("onblur", "WatermarkBlur(this, '" + strWatermarkSearch + "');");

We can see the perfect watermark implementation with our search textbox now! Happy Programming!

Liked the post? You can share this post by submitting to dzone,digg,dotnetkicks etc. You can even leave your suggestions as the comment below.


kick it on DotNetKicks.com

Friday, March 6, 2009

Using JavaScript for Validation of Different Date Formats in Asp.NET Web Form

Most often asp.net web applications need to validate date in a form. It is not that easy to play with different format of dates at different places. Mostly the mm/dd/yyyy (alternatively, mm-dd-yyyy) format of date is used. But we may need to go dd/mm/yyyy (alternatively, dd-mm-yyyy) also, and yyyy/mm/dd (alternatively, yyyy-mm-dd) format is no exception too. This article will discuss how to validate date in all these formats using simple yet powerful javascript code snippet.


Fig 1: Using ajax calendar extender to pick date into asp.net textbox in dd-mm-yyyy format



Fig 2: Validation of the date in the textbox in dd-mm-yyyy format on form submit

Let's start with the addition of a TextBox and an ajax calendarextender in a page.


Remember, we need ajax enabled page to use the calendar extender. Note that I have set the format in the calendarextender to dd-MM-yyyy. This will put the date in the targetcontrol (here, txtPurchaseDate) in dd-mm-yyyy format. On client click of the button btnSubmit, the javascript function ValidateForm() will validate the date in the textbox. If it is not in dd-mm-yyyy format, a message will be alerted as in the figures above.

Here are the functions Validateform() and validateInputDate().

function ValidateForm()
{
if(document.getElementById("txtPurchaseDate"))
{
if(validateInputDate(document.getElementById("txtPurchaseDate").value)==false)
{
alert("Please input purchase date in the format dd-mm-yyyy.");
return false;
}
}
}



//Validates date in the format dd-mm-yyyy (e.g. 19-10-2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\-.](0[1-9]1[012])[\-.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

Now we can change the validateInputDate() date validation function to validate other date formats. Listed below are the functions for validating different date formats.


//Validates date in the format dd/mm/yyyy (e.g. 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\/.](0[1-9]1[012])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}


//Validates date in the format dd-mm-yyyy or dd/mm/yyyy (e.g. 19-10-2009 or 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\- \/.](0[1-9]1[012])[\- \/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format mm/dd/yyyy (e.g. 10/19/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format yyyy-mm-dd or yyyy/mm/dd (e.g. 2009-10-19 or 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\- \/.](0[1-9]1[012])[\- \/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format yyyy-mm-dd (e.g. 2009-10-19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\-.](0[1-9]1[012])[\-.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format yyyy/mm/dd (e.g. 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\/.](0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}

Happy Programming!
Liked the post? You can kick it on DotNetKicks.com and and

Monday, February 9, 2009

Upload and Crop Images with jQuery, JCrop and ASP.NET

Need to crop image before uploading, in asp.net? Sounds like the alternative to thumbnail generation in asp.net web page, right? Here goes the handy code using jQuery, JCrop and ASP.NET. Good luck!

I have coded a shopping cart in which there was the need of uploading images to the server, and keep the sizes as required by the content of the pages. In my case I had to hard-code the size of the thumbnail I generated. But wouldn't it be lovely if the site user could crop the image and fix the required size? So I have found one very useful way to Upload and Crop Images with jQuery, JCrop and ASP.NET. I hope this will be useful for all programmers.

Happy Programming!

Wednesday, January 28, 2009

Open New Window in ASP.NET web page using JavaScript

I have found much tricks in different tutorials and forums on opening new window in asp.net web page, using JavaScript, jquery etc. Here I have put most useful of ways to open new window (and pop-up window) in asp.net web page. I hope these tricks will be helpful.
After learning different ways of opening new window in asp.net, you may learn How to refresh parent page from child window in asp.net using javascript, in a later post that follows. At the same time, if you are using iframe and have a need of Refreshing parent page partially by calling javascript function in parent page, you can see it with code snippets in another post. For now here I have put ways to opening new asp.net page. And before continuing, I would like to inform that there is a post regarding Frequent question on parent and child page refresh, reload, function call in asp-net using javascript that discusses, in aggregate, about some more approaches of parent and child page operations.
1. Open New Window from HyperLink control
<asp:hyperlink id="hyperlink1" runat="server" navigateurl="~/Default.aspx" target="_blank"></asp:HyperLink>
Clicking this hyperlink will open the Default.aspx page in new window. In most of the cases this simple coding can save need of lots of JavaScript code!
2. Open New Window on Button Click
<asp:button id="btnClck" runat="server" onclick="btnClick_Click">
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
string url = "MyNewPage.aspx?ID=1&cat=test";
string fullURL = "window.open('" + url + "', '_blank', 'height=500,width=800,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
btnClck.Attributes.Add("OnClick", fullURL);
}
}
Here, on page load, script has been added to the attribute of the button ‘btnClick’. According to the script, height and width of the pop-up window has been fixed. Toolbar will not be shown (toolbar=no). Similarly, the window will be non-resizable. Please note that the properties can be set as required. New window of the designated properties will open on click of the button. I have shown the use of custom destination URL in the script by using ‘url’ and ‘fullURL’ string variables.
I have noted that the window will be resizable (hence uncontrollable) in Mozilla Firefox.
3. Open New Window using ScriptManager
Just on button click, we can register the script to open new window. Let me show this on button click event hander.
protected void btnClick_Click(object sender, EventArgs e)
{
string url = "MyNewPage.aspx?ID=1&cat=test";
string fullURL = "window.open('" + url + "', '_blank', 'height=500,width=800,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);
}
Here we don’t need to add attribute to the button. This just will open new window with the URL specified. And please also note the properties of the new pop-up window.
4. Open New Window using ClientScriptManager
This method is much alike the previous one. Only difference is we user ClientScript class in place of ScriptManager class.
protected void btnClick_Click(object sender, EventArgs e)
{
string url = "MyNewPage.aspx?ID=1&cat=test";
string script = "window.open('"+url+"','')";
if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "NewWindow", script, true);
}
}
Here new window will open keeping the parent one intact.
All these four methods are try-worthy. I have been across all these methods of opening new window in asp.net web page and found easy and code-friendly to use.
Happy Programming!
Shout it

Sunday, October 26, 2008

Windows Forms like Messagebox in asp.net web page

I have often come accross web pages where web programmers resent they miss the MessageBox that is available and highly used in windows programming. And for sure I am no exception. While searching for MessageBox functionality in asp.net web page, I have found one which is quite simple and useful.

Note the MessageBox function in the code snippet below. It takes a string as a parameter and pops it up in a messagebox window using asp.net Label control and javascript. For illustration of it's use, I have added a textbox with ID txtName and a button with ID btnOK. User enters his/her name in the textbox and clicks ok. If the user input contains special characters &, _ or @, the messagebox will be prompted with the message that name can not contain such charaters. If not, user's name will be prompted using same message box.
Fig: Displaying windows form like MessgeBox in asp.net web page

Here goes the MesageBox function in C#, which we can call anytime. It takes the message text (string) as input and displays as in the figure above. The only trick involved is:
1. Create a new label from code behind
2.Initialize the text of the lable to a little javascript code [which is a call to javascript's alert function].
3. Add this label to to the page's control bag.

That's all. Now lets look into the function itself.


//the message box function
private void MessageBox(string msg)
{
Label lbl = new Label();

lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";

Page.Controls.Add(lbl);
}


Now lets go with an example. We will have a form in which there is one textbox and one button. We will message user when undesired special character is detected in the textbox. Lets have the form markup like this [within the form].


<body>

<form id="form1" runat="server">

<div>

<asp:Label ID="Label1" runat="server" Text="Your Name:"></asp:Label>

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

<asp:Button ID="Button1" runat="server" Text="OK" onclick="Button1_Click" />

</div>

</form>

</body>


Now is the time for the event handler on button click.

//invoked when button btnOK is clicked
protected void Button1_Click(object sender, EventArgs e)
{
string name = txtName.Text;
if (!ValidateString(name))
{
MessageBox("You can not put special characters _, & or @ in your name.");
}
else
{
MessageBox("Your name is" + " " + name);
}
}


This is just another function for test purpose only, that validates the characters in the textbox.


//returns true if the string contains _,& or @
//otherwise returns false
public bool ValidateString(string str)
{
if((str.Contains("_") || (str.Contains("&"))||(str.Contains("@"))))
{
return false;
}
else
return true;
}


This MessageBox function, although a simple one can be extensively used throughout the pages, using MasterPage concept or base page concept or anything else that propagates inheritance. The only limitation is that for this method to work javascript must enabled in the browser (and you know this is the issue in all pages that use javascript). Further, for the function ValidateString, which currently checks only three special characters, you can extend it to include other special charactes also.


Your creative suggestions are always welcome! Happy programming!
kick it on DotNetKicks.com

Popular Posts

Recent Articles