无法获取下拉列表ASP.NET的SelectedValue

时间:2015-03-20 19:46:26

标签: asp.net

好的,当我点击时想要获取下拉列表的SelectedValue 一个按钮,但SelectedValue总是返回“”(没有), 请帮帮我谢谢!

这是源

    <tr>
    <th style="float:left">
    <asp:DropDownList ID="ddlcategory" runat="server" ></asp:DropDownList>
    <asp:TextBox ID="txtsearch" runat="server"></asp:TextBox>
    <asp:ImageButton ID="btnsearch" runat="server" Height="20px" ImageUrl="~/img/search.png" OnClick="btnsearch_Click" Width="20px" />
    <asp:LinkButton ID="lbtnsearch" runat="server" PostBackUrl="~/Search.aspx">Advanced Search</asp:LinkButton>
    </th>
    </tr>

以下是

背后的代码
    public partial class _default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    SqlDataAdapter adapter = new SqlDataAdapter();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDataList();
            BindDropDown();
        }
    }

    private void BindDataList()
    {
        string cmd = "SELECT top 3 product_id, product_name, brand, imgurl FROM product ORDER BY NEWID()";
        adapter.SelectCommand = new SqlCommand(cmd, con);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        DataList1.DataSource = dt;
        DataList1.DataBind();
    }

    private void BindDropDown()
    {
        string cmd = "select category_id, category_name from category";
        adapter.SelectCommand = new SqlCommand(cmd, con);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        ddlcategory.DataTextField = "category_name";
        ddlcategory.DataValueField = "category_id";
        ddlcategory.DataSource = dt;
        ddlcategory.DataBind();
    }

    protected void btnsearch_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("~/Product/Product.aspx?category_id=" + ddlcategory.SelectedValue.ToString() + "&search=" + txtsearch.Text);
    }
}

这是我点击btnsearch的结果 “http://localhost:1345/Product/Product.aspx?category_id=&search=something” 你可以看到那个ddlcategory.SelectedValue.ToString() 返回“”,出了什么问题?

1 个答案:

答案 0 :(得分:1)

该死的,我花了几个小时,最后解决了这个问题。 问题是在母版页(父控件)中将EnableViewState设置为false。而你所需要的只是将它重新设置为真。即使DropDownList(子控件)启用了viewstate,它也需要在父控件上确定。即,父控件中的EnableViewState设置为false,子控件也将为false。