2009-04-11 17 views
1

我有問題從FIndControl函數獲取dropdownlist的值。幫助:無法投出對象Dropdownllist到IConvertible

這裏是代碼我想使用:

currentCategoryID = Convert.ToInt32(((DropDownList)r.FindControl("DDLCategories"))); 

的currentCategoryID在數據庫中的值是一個「INT」

當我執行上面的代碼我收到此錯誤信息:

無法投射「System.Web.UI.WebControls.DropDownList」類型的對象以鍵入「System.IConvertible」。

使用相同的代碼,我不得不使用此代碼retireve文本框的值,一切都OK

currentAddress = ((TextBox)r.FindControl("txtAddress")).Text; 

可能有人請指出我如何編寫這段代碼正確

回答

3

你試圖將DropDownList將其轉換爲Int32,而不是它的價值。在轉換之前,您應該進一步鑽取控件以檢索該值。例如,

currentCategoryID = Convert.ToInt32(((DropDownList)r.FindControl("DDLCategories")).SelectedItem.Value); 
+0

謝謝沃爾特,我知道這是簡單的東西,我正在努力。 – Jason 2009-04-11 22:53:14

1

正確的方向您的第一個片段試圖將DropDownList控件本身轉換爲int。你需要做的是提取選擇的值或所選項目或什麼的,這取決於你使用的UI框架:

object selectedId = ((DropDownList)(r.FindControl("...")).SelectedValue; 
int currentCategoryId = Convert.ToInt32(selectedId);