2010-10-18 38 views
1

neI具有帶有值列表的DropDownList。如何轉換INT變量中的DropDownList值變量

我需要在我的代碼中使用用戶在DropDownList AS INT數據類型(數字)中選擇的值。

目前我在下面使用此代碼(轉換數據)。 腳本工作就好了。

但是我想知道是否存在替代方法來做到這一點

任何想法,這是非常感激。謝謝你的時間。


<asp:DropDownList ID="uxPageSizeUsersSelector" runat="server" 
    AutoPostBack="True" 
    onselectedindexchanged="uxPageSizeUsersSelector_SelectedIndexChanged"> 
    <asp:ListItem Value="1" Selected="True">1</asp:ListItem> 
    <asp:ListItem Value="2">2</asp:ListItem> 
    <asp:ListItem Value="3">3</asp:ListItem> 
    <asp:ListItem Value="4">4</asp:ListItem> 
</asp:DropDownList> 

 int myPageSize = Convert.ToInt16(uxPageSizeUsersSelector.SelectedValue.ToString()); 
     PageSize = myPageSize; 
+1

請注意,將值賦給變量時,實際上將值轉換爲「short」,然後轉換爲「int」。 'short'是'Int16','int'是'Int32'。 – 2010-10-18 14:47:29

+0

您不需要調用'SelectedValue.ToString()',因爲'SelectedValue'已經是一個字符串。有什麼理由爲什麼你要轉換成Int16而不是Int32?否則,這確實是這樣做的方式。 – 2010-10-18 14:48:06

+0

感謝傢伙它有道理! – GibboK 2010-10-18 15:07:44

回答

4

您可以使用try parse方法。這將確保你的價值是一個int,如果沒有,讓你來處理,而不是拋出一個異常的問題:

int myPageSize; 

if(int.TryParse(uxPageSizeUsersSelector.SelectedValue, out myPageSize)) 
{ 
    //SUCCESS 
} 
else 
{ 
    ///handle problem here. 
} 

可以爲Int16的日期時間等,做到這一點。