无论选择什么,asp.net中DropDown的SelectedItem总是显示相同的值

时间:2014-10-13 08:04:32

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

我有一个asp.net的下拉列表控件。我想跟踪下拉列表中选择的项目。让我展示一下我做了什么。

这是DropdownList控件:

<asp:DropDownList ID="Dd_Cat" runat="server" 
         DataValueField="CatId" DataTextField="CatName" 
         OnSelectedIndexChanged="wtf"  >
</asp:DropDownList>

这是用于从数据库填充dropdownlist的代码。

protected void bindDropdown()
{
   string mystr = ConfigurationManager.ConnectionStrings["str"].ConnectionString;
   SqlConnection con = new SqlConnection(mystr);
   con.Open();
   SqlCommand cmd = new SqlCommand("AddCat", con);
   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.AddWithValue("@action", "select");
   SqlDataAdapter da = new SqlDataAdapter(cmd);
   DataSet ds = new DataSet();
   da.Fill(ds);
   Dd_Cat.DataSource = ds;
   Dd_Cat.DataBind();
   con.Close();
   con.Dispose();
}

onselected控件的dropdownlist属性:

protected void wtf(object sender, EventArgs e)
{
  string st = Dd_Cat.SelectedValue;
}

这总是显示价值&#34; 1&#34; nomatter是什么选择。请帮助。

1 个答案:

答案 0 :(得分:3)

我假设您在bindDropdown中呼叫Page_Load而未使用!IsPostBack - 请检查。然后,您始终加载默认值,并且SelectedIndexChanged事件未被触发。

因此,如果EnableViewState设置为true(默认值),请使用此选项:

protected void Page_Load(Object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        // page is loaded the first time, load from database
        bindDropdown();
    }
}

阅读:Page.IsPostBack

相关问题