ASP.NET Dropdrownlist与SelectValue Assignment一起发布

时间:2011-06-17 02:20:16

标签: asp.net drop-down-menu

这是我的aspx

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <asp:ObjectDataSource ID="DSCategories" runat="server" 
        SelectMethod="GetCategories" TypeName="BAL.CategoryBAL">
    </asp:ObjectDataSource>

    <div id="Criteria">
        <h3>Category:</h3>
        <asp:DropDownList ID="ddlCategories" runat="server" 
            DataSourceID="DSCategories" DataTextField="Description" 
            DataValueField="Code">
        </asp:DropDownList>
        <asp:Button ID="btnSetCriteria" runat="server" Text="Set Criteria" />

    </div>

</asp:Content>

这是我的Page_Load代码:

SearchCriteriaBAL scb = SearchCriteriaBAL.GetSearchCriteria(id);

string cat = String.Empty;
if (!string.IsNullOrEmpty(scb.Criteria))
{
    cat = ParseCriteria(scb.Criteria);

    ddlCategories.SelectedValue = cat;
}

我打破了SelectedValue分配行,看到了下拉列表中的项目,我看到了cat的有效值,它在列表中但是我得到了:

  

'ddlCategories'有一个SelectedValue   这是无效的,因为它没有   存在于项目列表中。参数   name:value

我设置了selectedValue之后似乎正在进行GetCategories,然后就死了。

我把它放在自己的测试页面上,因为担心交互,但它仍然失败。有没有人见过这个?

2 个答案:

答案 0 :(得分:2)

您可以尝试以这种方式选择项目:

ddlCategories.Items.FindByValue(cat).Selected = true;

如果cat集合中Items确实不存在,那么这当然不会起作用

答案 1 :(得分:1)

在DropDownList的DataBound事件而不是Page_Load

上编写该函数
  

在服务器控件绑定后发生   到数据源。

<asp:DropDownList ID="ddlCategories" runat="server" 
    DataSourceID="DSCategories" 
    DataTextField="Description" 
    DataValueField="Code"
    OnDataBound="ddlCategories_DataBound">
</asp:DropDownList>

我会选择

,而不是使用SelectedValue
ddlCategories.Items.FindByValue(cat.Trim()).Selected = true;