0

I have two pages ConnectHome and ConnectNext and i want to connect ConnectHome to ConnectNext page using crosspage Postback. But i am not able to create the instance of ConnectHome class in ConnectNext code page. Here is my code :

protected void Page_Load(object sender, EventArgs e)
    {
        ConnectHome prevPage = (ConnectHome)(this.PreviousPage);
        if (prevPage != null)
        {
            Label1.Text = prevPage.name;
            Label2.Text = prevPage.email;
            Label3.Text = "You landed this page from " + prevPage.Title.ToString();
        }
        else
        {
            Label3.Text = "You directly landed to this page";
        }
    }

1 Answers1

1

Instead of doing casting like that, try using the as syntax to avoid an invalid cast exception.

ConnectHome prevPage = this.PreviousPage as ConnectHome;
if (prevPage != null)
        {
            Label1.Text = prevPage.name;
            Label2.Text = prevPage.email;
            Label3.Text = "You landed this page from " + prevPage.Title.ToString();
        }
        else
        {
            Label3.Text = "You directly landed to this page";
        }

When you use the as syntax, it will convert if it's a valid type. If not, the object will be null. For more info, see this question.

Community
  • 1
  • 1
mason
  • 31,774
  • 10
  • 77
  • 121
  • its showing error that 'the type or namespace ConnectHome could not be found' – user3409204 Jul 02 '14 at 17:58
  • That means your page is in a different namespace. Either put them in the same namespace, or add a using statement to the top of `ConnectNext.aspx.cs` such as `using MyWebsiteNamespace;` – mason Jul 02 '14 at 18:01