CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
5 Useful Tips for ASP.Net Application

By Satheesh babu
Posted On Sep 10,2008
Article Rating:
Be first to rate
this article.
No of Comments: 20
Category: ASP.Net
Print this article.

5 Useful Tips for ASP.Net Application

 

Introduction

There are so many tasks/operations that are repeatedly done in ASP.Net applications. This article will list some of the useful tasks that we can use in our asp.net application extensively.

1.      Get Extension from Path/URL.

2.      Clearing input controls at a stretch in ASP.Net.

3.      Get Control Name in JavaScript When Using MasterPages.

4.      Invoking an Event in ASPX Page from UserControl.

5.      Selecting/Highlighting the TextBox Value If Validation Fails.

 

Get Extension from Path/URL

Most often, we will get requirement to extract extension of a link in C#. The below code does that easily.

string ext = System.IO.Path.GetExtension(@"F:\Articles\ASP.Net Tips\tips.doc");

or

string ext = System.IO.Path.GetExtension(@"http://www.codedigest.com/Articles/ASPNETAJAX/127_Tips_and_Tricks_-_ASPNet_AJAX_Applications.aspx");

 

Clearing input controls at a stretch in ASP.Net

There will be situations where we will develop an input form for bulk input processing. Obviously, these forms will have large number of input controls like textbox, dropdownlist, checkbox and radiobutton, etc. In such forms, we need to reset these control once the input is processed for the subsequent request. You can use the below code to reset the input controls at a stretch instead of clearing it one by one.

 

[Updated code as per the user comments - Thanks to gramotei and Sean]

 

private void btnClear_Click(object sender, System.EventArgs e)

{

Control myForm = Page.FindControl("Form1");

        foreach (Control ctrl in myForm.Controls)

        {

            //Clears TextBox

            if (ctrl is System.Web.UI.WebControls.TextBox)

            {

                (ctrl as TextBox).Text = "";

            }

 

            //Clears DropDown Selection

            if (ctrl is System.Web.UI.WebControls.DropDownList)

            {

                (ctrl as DropDownList).ClearSelection();

            }

 

            //Clears ListBox Selection

            if (ctrl is System.Web.UI.WebControls.ListBox)

            {

                (ctrl as ListBox).ClearSelection();

            }

 

            //Clears CheckBox Selection

            if (ctrl is System.Web.UI.WebControls.CheckBox)

            {

                (ctrl as CheckBox).Checked = false;

            }

 

            //Clears RadioButton Selection

            if (ctrl is System.Web.UI.WebControls.RadioButtonList)

            {

                (ctrl as RadioButtonList).ClearSelection();

            }

 

            //Clears CheckBox Selection

            if (ctrl is System.Web.UI.WebControls.CheckBoxList)

            {

                (ctrl as CheckBoxList).ClearSelection();

            }

        }

}

 

Get Control Name in JavaScript

When we use masterpage in ASP.Net, it will append the ContentPlaceholderId with the ID of the controls that is inside the Content tag during HTML rendering. For example, when there is a textbox with ID “txtAccountNumber” it will be rendered as “ctl00_ContentPlaceHolder1_txtAccountNumber” to the client, where “ContentPlaceHolder1” is the ID of the Content Placeholder of the Master Page. This behaviour is again seen when we use user controls.

 

To access any control in JavaScript we use,

document.getElementById(' ID') ;

 

In our case, it will be similar to,

document.getElementById(' ctl00_ContentPlaceHolder1_txtAccountNumber ')

 




The above statement will lead to script error if we unknowingly change the ID of the ContentPlaceholder or move the control to different ContentPlaceholder in the Page. Hence, whenever ContentPlaceholder ID is changed we need to revisit all the Jscript code and change the corresponding ID’s. To prevent this rework, we can register a hidden control from code behind which in turn will hold the client ID of the control.

 

Page.RegisterHiddenField("hdnAccountNoTextID", txtAccountNumber.ClientID);

 

Now we can make use of this hidden variable to get the client ID of the textbox in Jscript.

 

//gets the Client ID of the txtAccountNumber textbox

    var AccountNoTextID = document.getElementById('hdnAccountNoTextID').value; //Access the txtAccountNumber textbox

    var AccountNoText = document.getElementById('hdnAccountNoTextID');

 

Thus, the changes in ID of the container controls will not affect our JavaScript codes.

 

Invoking an Event in ASPX Page from UserControl

Consider we have a button in a UserControl. For example, if we need to raise an event in aspx page for every button click in user control, we need to declare an event in user control which should be registered with the event handler in the aspx page. Refer the below code.

 

UserControl

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>

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

 

UserControl CodeBehind

public partial class WebUserControl : System.Web.UI.UserControl

{

    public event EventHandler usrCtrlButtonClick;

 

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        usrCtrlButtonClick.Invoke(this, new EventArgs());

    }

}

 

ASPX Page

 protected void Page_Load(object sender, EventArgs e)

    {

 

        this.WebUserControl1.usrCtrlButtonClick += new EventHandler(this.usrctrlButtonClick);

   }  

 

    protected void usrctrlButtonClick(object sender, EventArgs e)

    {

        Response.Write("From aspx page");

    }

 

Selecting/Highlighting the TextBox Value If Validation Fails

Consider we have a validation JavaScript method which checks for the validity of the data entered in a TextBox. When the validation fails, we will alert or display a error message to the user and call focus() method on the control to let the user know the control on the page. At times, we will require select or highlight the invalid data instead of returning the focus to the control. Refer the below figure.

 

This can be achieved by calling the select() method on the control. Refer the below code,

 

document.getElementById('txtAccountNumber').select();

 

Conclusion

Thus, we have seen of the useful utility method which we can repeatedly use fin our asp.net projects. I will continue this article with more and more such task in future articles. Thanks for reading this article.

Happy Coding!!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Clearing input controls at a stretch in ASP.Net
thanks ..."Clearing input controls at a stretch in ASP.Net" is the best one !!!
waiting for more Tips.
Nice Explaination
Really very nice explanation of each and every topic...

Thank you very much...
RE:Accessing other Controls
hmm..passing the form and to traverse the DOM to find a control seems to be not a better idea..I remember developing a form where we had many number of textbox and input controls, this approach will increase the complexity..
I accept, we can pass the form object and can traverse the DOM but i would rather try to decrease the complexity in these things to really work on application complexities..
Accessing other Controls
You should be able to pass the form into the function and use ChildNodes in Javascript to traverse the DOM.

I haven't tried this, but should work. You would have to specifically check the type of object. You could use getElementByTagName <- may want to double check case of this, to get objects that are of type input/a/div etc.
RE:A few comments.
Thanks for the suggestions..its really great!
Jus a point, passing this to function in external javascript file serves the need if we require access only to that control. What if we want access the other page controls in the same function??
A few comments.
in your page you have a few options (function could exist in js file)
You could always pass to your function with this -> ex. onclick="return SomeFunction(this);"

or if you need to get it in a specific function in the page
var obj = document.getElementById('<%=this.SOMECONTROL.ClientID%>')

Clearing Input Controls
I would break out the foreach into another method and loop...You need to make sure that the ctrl.HasControls and loop through those too.
void ClearControls(Control ctrl)
{
//do stuff
if (ctrl.HasControls())
ClearControls(ctrl);
}


if you need to do a postback from within javascript in the page
__doPostBack('<%=this.SOMECONTROL.UniqueID %>','')

Also a bigger fan of (ctrl as TextBox).Text = String.Empty;
Form element
Concerning the line:
'Control myForm = Page.FindControl("Form1");'

Surely, you'll have access to the Form object that the button lives on, so you can actually just use 'Form' without 'this' as a prefix.

Using the line you state increases the risk of the form not being found if it has been renamed and is also unnecessary I believe?

So you could do:

foreach (Control ctrl in Form.Controls)

instead.
Very Nice
Too good! It is very useful to me! Good Article!
Re:Clearing input controls
Hi Kalpesh, Thanks for the feedback. Not every time we can use a reset button to clear input controls on the page. Most of the time, once the data is saved to the database we will load the screen freshly without any previous typed in data. Also, consider gramotei and Sean feedback to use "is" keyword for type checking rather than using the string comparsion. Thanks again!
RE:Nice Intent, Wrong Approach
Hi Sean, Thanks for your valuable feedback. I agree, using "is" keyword for type checking is better approach than converting to toString for comparison.
Nice Intent, Wrong Approach
Your intention was good, but you would benefit from learning how to use the "is" and "as" keywords and learn how inheritance works. Your btnClear_Click event handler needs to be rewritten using proper OOP techniques. GetType().ToString() is definitely the wrong approach.
Clearing input controls
In what case, would one clear the input controls? This could be done at client side using a Reset button.
Using control.ClientID
You can use document.getElementById('<%# txtAutoComplete.ClientID %>'). This will work even with dynamic controls. Of course you need to call Page.DataBind in Page_Load.
RE: jrummmell, RyanOC
Adding to AdamC feedback, <%= txtAccountNumber.ClientID %> will work only if we write out JScript code in ASPX file. If we have separate JavaScript file and include it in our page then it may not work..@gramotei, @configurator - thanks for your feedback. Using "is" is really good! Since type of ctrl is known only during runtime it is not possible to get compile time error! Thanks again!
RE: jrummmell, RyanOC
> document.getElementById('<%= txtAutoComplete.ClientID %>'); It doesn't work if you're adding controls dynamically in your code behind. Compilation error.
ClientID
the comment system stripped out the <%= txtAccountNumber.ClientID %gt;
ClientID
You could also use document.getElementById('<%= txtAccountNumber.ClientID %>');
ClientId
How about this for getting a client id from javascript? var myTextBox = document.getElementById('<%= txtAutoComplete.ClientID %>');
GetType().ToString() ?
ctrl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox")? WTF? Why not use: ctrl.GetType() == typeof(System.Web.UI.WebControls.TextBox) which would give you compile-time checks for the type? Or ctrl is System.Web.UI.WebControls.TextBox which is the proper way to do that?
type check
For type check I would use "if (ctrl is ListBox)"