DropDownList SelectedValue不会更改

时间:2011-08-08 18:47:46

标签: c# asp.net drop-down-menu

在我调用searchBtn_Click的页面中,只有选择没有改变时,selectedvalue才会进入变量ind。因此,如果用户选择汽车,然后单击搜索按钮,然后他们将选择更改为政府,它将刷新页面并显示汽车,我是否在回发中丢失了某些内容或在此处做错了什么?

    protected 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);
    }

4 个答案:

答案 0 :(得分:3)

只需使用此代码替换您的代码

      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;
            }
        }
      }
    }

答案 1 :(得分:0)

您不需要使用Redirect和QueryString。 在Page_PreRender处使用SelectedValue(在您的示例中完全清除Page_Load)。

答案 2 :(得分:0)

你最好在搜索按钮中点击

但请记住你的dropdowndlist的value-member == display-member要做到这一点..我有同样的问题,这就是我解决它的方法。

string ind = IndustryDropDownList.Text.Tostring().Trim();
Response.Redirect("Default.aspx?ind=" + ind);

我知道这不是最好的方式,但它对我有用..

答案 3 :(得分:0)

你没有利用asp.net表单的ViewState(虽然MVC 3的心态很好)。但是由于您使用的是asp.net,因此您应该将代码更改为:

除非您希望用户将行业设置为进入页面,否则不必加载页面中的逻辑。自从我假设你做了,我在那里留下了一些逻辑。它会检查回发,因为它不需要在初始页面加载后执行。

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;
}

您不必重定向页面,因为每次页面回发时都会调用Page_Load。使用.NET,您的控件会自动记住它们的最后一个值。

protected void searchBtn_Click(object sender, EventArgs e)
{
    SetIndustry(IndustryDropDownList.SelectedValue);
}