开发者

ASP.NET Dropdrownlist croaks with SelectValue Assignment

This is my aspx

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

    <asp:ObjectDataSource ID="DSCategories" runat="server" 
        SelectMethod="GetCateg开发者_如何学Goories" 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>

And this is briefly my Page_Load code:

SearchCriteriaBAL scb = SearchCriteriaBAL.GetSearchCriteria(id);

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

    ddlCategories.SelectedValue = cat;
}

I break on the SelectedValue assignment line and see the items in the dropdownlist and I see a valid value for cat and it is in the list but I get:

'ddlCategories' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value

It seems to be doing the GetCategories AFTER I set the selectedValue and then it dies.

I placed it on its own test page for fear of interaction but it still fails. Has anyone seen this before?


You could try selecting the item this way:

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

Which of course wont' work if cat really isn't in the Items collection


Write the function on DropDownList's DataBound event instead of Page_Load

Occurs after the server control binds to a data source.

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

Rather than using SelectedValue, I would have opted

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜