"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Thursday, February 3, 2011

Getting value from previous page OR Cross page PostBack

hi,
Getting value from previous page, it's simple use query-string is it? did u every noticed the url then. its look like a sexy model with grass on ass.I hate that.On my current project i faced this problem. when i c that i was shocked that's killing my project. my browser can't display it's fully. For some data i can't. 
                                       Then i made a study over postback it's ended in a ocean. Dot NET is providing 100 ways to solve this problem then i don't know y everyone running after this fucking query-string. among those i scrabbled 2 simple way's.


Method 1


Suppose i have 2 pages [ Page1.aspx, Page2.aspx
On Page1.aspx create 2 text-box and a button like this


   First Name :
   <asp:TextBox ID="txt_Fname" runat="server"></asp:TextBox><br />
   Second Name :
   <asp:TextBox ID="txt_Lname" runat="server"></asp:TextBox><br />
   <asp:Button ID="btn_Save" runat="server" PostBackUrl="~/page2.aspx"
    Text="Submit" OnClick="btn_Save_Click" />

on button add PostBackUrl="~/page2.aspx"  

on Page2.aspx.cs add this code on page load Event

    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        {
            TextBox txtPFname = (TextBox)PreviousPage.FindControl("txt_Fname");
            TextBox txtPLname = (TextBox)PreviousPage.FindControl("txt_Lname");
            lblMsg.Text="Welcome :'"+txtPFname.Text+"'"+txtPLname.Text+"";

        }
    }


Method 2

Suppose i have 2 pages [ Default1.aspx, Default2.aspx ]

On Default1.aspx add 2 textbox and 1 button like Method 1

        First Name :
        <asp:TextBox ID="txt_Fname" runat="server"></asp:TextBox><br />
        Second Name :
        <asp:TextBox ID="txt_Lname" runat="server"></asp:TextBox><br />
        <asp:Button ID="btn_Save" runat="server" PostBackUrl="~/Cross Post Back/page2.aspx"
        Text="Submit" OnClick="btn_Save_Click" />

On default1.aspx.cs add this code

 public TextBox txtpFname
    {
        get
        {
            return txt_Fname;
        }
    }
    public TextBox txtpLname
    {
        get
        {
            return txt_Lname;
        }
    }


On default2.aspx add this line on top 

<%@ PreviousPageType VirtualPath="Default1.aspx" %>


and on default2.aspx.cs, on pageload event add these lines 




    {
        if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        {
            lblMsg.Text = "Hai," + PreviousPage.txtpFname.Text + " "+PreviousPage.txtpLname.Text+"";
        }
    }


Hope these help u some way :)

Have a nice day... 'N happy Coding :)

No comments: