Friday 16 March 2012

Strongly type instead of FindControl

Problem
You can use FindControl method to find a control in your previous page, but you have to cast to get the control and if anything goes wrong (for instance: the type or control name is misspelled), you will get the error at runtime.
Impact
I will like to use a different and secure way to access the controls values from the previous page, where I can get any errors at compile time.

Solution
You can use the Strongly Type method to access the data from previous page. You can follow the following steps:
 
1. In the previous page form where you have the controls to access, you have to create the public properties for each control that will return the value you want.

   public string FirstName  
    {
        get { return TextBoxFName.Text; }
        set { TextBoxFName.Text = value; }
    }

    public string LastName
    {
        get { return TextBoxLName.Text; }
        set { TextBoxLName.Text = value; }
    }

    public string Email
    {
        get { return TextBoxEmail.Text; }
        set { TextBoxEmail.Text = value; }
    }

2. Add the PreviousPageType directive in the page where you will work with the data to access to the previous page controls:
 <%@ PreviousPageType VirtualPath="~/ContactUs.aspx" %>

3. Finally, you can access to the value of the controls from the previous page utilizing PreviousPageName.PropertyName:

Label1.Text = "Thanks " + ContactUs.FirstName + " " + ContactUs.LastName + " for contact us. You will receive a message to your" + ContactUs.Email + " from our company soon." + System.Environment.NewLine;


Conclusion
Avoid using FindControl method, try to use the Strongly Type method to access the data from previous page. You will get the errors at compile time, and it will  be a secure and flexible method to use.

No comments:

Post a Comment