aantiix
aantiix

Reputation: 534

Display variable in textbox

In my ASP.NET page I have a search box that is currently working as expected. What I would like to do is leave the searched value in that textbox after searching (the search opens a new page, though I'm retaining the search value from querystring). I can confirm the variable is being retained correctly by using the value <%= search%> in my aspx, however when I try to show that in my textbox nothing displays. I have searched dozens of forum posts and the nearest I can tell is that I need to databind this textbox. I'm not sure where my mistake is, but this is the closest I have come up with:

<asp:TextBox ID="SearchTextBox" runat="server" Text='<%# search %>'></asp:TextBox>
Search: <%=search %>

With the code behind

public string search;

protected void Page_Load(object sender, EventArgs e)
{
    search = Request.QueryString["search"];
    SearchTextBox.Text = search;
    Page.DataBind();
}

Upvotes: 1

Views: 372

Answers (2)

Boxiom
Boxiom

Reputation: 2305

Try this:

if (Request.QueryString["search"] != null && !IsPostBack)
{
     string search = Request.QueryString["search"];
     SearchTextBox.Text = search;
}

Upvotes: 0

Juan
Juan

Reputation: 1382

You have to check if it is the first time you see the page with this

 if (Page.IsPostBack == false)
        {

}

And check first if the query string exist.

Upvotes: 1

Related Questions