Get Textbox Value from Masterpage using c#

ⅰ亾dé卋堺 提交于 2019-12-13 05:26:06

问题


I have a search textbox situated on a masterpage like so:

<asp:TextBox ID="frmSearch" runat="server" CssClass="searchbox"></asp:TextBox>
<asp:LinkButton ID="searchGo" PostBackUrl="search.aspx"  runat="server">GO</asp:LinkButton>

The code behind for the search page has the following to pick up the textbox value (snippet):

if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        {
            Page previousPage = PreviousPage;
            TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("frmSearch");
            searchValue.Text = tbSearch.Text;

            //more code here...
        }

All works great. BUT not if you enter a value whilst actually on search.aspx, which obviously isn't a previous page. How can I get round this dead end I've put myself in?


回答1:


If you use the @MasterType in the page directive, then you will have a strongly-typed master page, meaning you can access exposed properties, controls, et cetera, without the need the do lookups:

<%@ MasterType VirtualPath="MasterSourceType.master" %>

searchValue.Text = PreviousPage.Master.frmSearch.Text;

EDIT: In order to help stretch your imagination a little, consider an extremely simple property exposed by the master page:

public string SearchQuery 
{
    get { return frmSearch.Text; }
    set { frmSearch.Text = value; }
}

Then, through no stroke of ingenuity whatsoever, it can be seen that we can access it like so:

searchValue.Text = PreviousPage.Master.SearchQuery;

Or,

PreviousPage.Master.SearchQuery = "a query";



回答2:


All you need is:

TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("frmSearch");
searchValue.Text = tbSearch.Text;

No need to worry about whatever 'previous page' is.

As @Mr.Disappointment also says you should look at having strongly-typed access.




回答3:


Here is a solution (but I guess its old now):

    {
        if (PreviousPage == null)
        {
            TextBox tbSearch = (TextBox)Master.FindControl("txtSearch");
            searchValue.Value = tbSearch.Text;
        }
        else
        {
            TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("txtSearch");
            searchValue.Value = tbSearch.Text;             
        }
    }


来源:https://stackoverflow.com/questions/7738693/get-textbox-value-from-masterpage-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!