2011-06-17 19 views
0

這是我的aspxASP.NET Dropdrownlist與SelectValue分配嘎嘎叫着

<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分配行並查看項目dropdownlist,我看到一個有效的值爲貓,它是在列表中,但我得到:

'ddlCategories'有一個SelectedValue 這是無效的,因爲它不存在於項目列表中 。參數 名:價值

這似乎是做GetCategories後,我設置了selectedValue,然後死去。

我將它放在自己的測試頁面上,以防止交互,但仍然失敗。有沒有人見過這個?

回答

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; 
+0

我剛剛嘗試過 - 這很有道理。但即使cat值在列表中,並且列表已填充,但我得到的Object引用未設置爲對象的實例。 – Jeff 2011-06-17 02:53:54

+0

Ohhh - 我發現它 - 我在貓值的末尾有一個空格,但它沒有在列表中找到它。非常抱歉,每個人的時間和幫助。 謝謝 – Jeff 2011-06-17 03:01:31

2

你可以嘗試選擇的項目是這樣的:

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

這當然不會」工作,如果cat還真是不Items集合中

+0

我得到一個NullReferenceException – Jeff 2011-06-17 02:46:30

+0

+1這應該被使用。不是SelectedValue。 – naveen 2011-06-17 04:28:21

相關問題