wizloc wizloc - 2 months ago 15
ASP.NET (C#) Question

How to implement a search bar on master page ASP.NET

I am trying to create a search bar for my ASP.NET pages that will be included in the master so it will be shown on all pages. Entering search text and hitting search will send you to results.aspx, which then retrieves the value of the text from the master page search box and displays data from the database in a grid view. Searching from my home page works fine, but I want the user to be able to enter a new search text while on the results page and have the page reload with the new data in the grid view.
Here is the code on results.aspx page load

if (PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)PreviousPage.Master.FindControl("txtSearchMaster");
if (SourceTextBox != null)
{
txtSearch.Text = SourceTextBox.Text;
}
}


Code on master page

<div id="search">
<asp:HyperLink ID="linkAddFile" runat="server" BorderStyle="None" NavigateUrl="~/Default.aspx" Width="150px" >Add File</asp:HyperLink>
<asp:TextBox ID="txtSearchMaster" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" PostBackUrl="~/results.aspx" />
</div>


The issue is once I get to the results page and try to do a new search from there, my conditional (PreviousPage != null) says that it is null.

Answer

Don't get the search values from the previous page via PreviousPage property.

Instead, when the user performs a search, grab the value from the search textbox and pass the value to the results page. Example:

master page

<div id="search">         
         <asp:TextBox ID="txtSearchMaster" runat="server"></asp:TextBox>
         <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
     </div>

Master Code behind

protected void btnSearch_Click(object sender, EventArgs e)
{
    var searchText = Server.UrlEncode(txtSearchMaster.Text); // URL encode in case of special characters
    Response.Redirect("~/Results.aspx?srch="+searchText);
}

Results page code behind

protected void Page_Load(object sender, EventArgs e)
{
    if(!String.IsNullOrEmpty(Request.QueryString["srch"])
    {
        //perform search and display results
    }
}