DropDownList SelectedValue doesn't Change
In my page when I call searchBtn_Click the selectedvalue will be carried into the variable ind only if the selection hasnt changed. So if a User selects Automotive, then clicks the search button, and then they change the selection to Government, it will refresh the page and display Automotive, am I missing something in the postback or doing something wrong here?
protec开发者_如何学编程ted void Page_Load(object sender, EventArgs e)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
protected void searchBtn_Click(object sender, EventArgs e)
{
string ind = IndustryDropDownList.SelectedValue;
Response.Redirect("Default.aspx?ind=" + ind);
}
Simply replace your code with this code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
}
You don't need to use Redirect and QueryString. Use SelectedValue at Page_PreRender (In your sample clear Page_Load completely).
you better try this in search button click
but remember your dropdowndlist's value-member==display-member to do this.. i had the same problem and this is how i solved it.
string ind = IndustryDropDownList.Text.Tostring().Trim();
Response.Redirect("Default.aspx?ind=" + ind);
i knw this is not the best way but it did work for me..
You're not leveraging the ViewState of asp.net forms (good mentality for MVC 3 though). But since you are using asp.net, you should change your code to this:
The logic in your page load is not necessary, unless you want the user to set the industry as the enter the page. Since I assumed you do, I left some logic in there. It checks for postback because it doesn't need to execute after the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack() && Request.QueryString["ind"] != null)
{
SetIndustry(Request.QueryString["ind"].ToString());
}
}
protected void SetIndustry(String industry)
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
You don't have to redirect the page, since Page_Load will be called every time the page posts back. With .NET, your controls remember their last values automatically.
protected void searchBtn_Click(object sender, EventArgs e)
{
SetIndustry(IndustryDropDownList.SelectedValue);
}
精彩评论