Skip to main content
 首页 » 编程设计

c#之如何转换 INT 变量中的 DropDownList 值

2024年02月24日25leader

我有一个带有值列表的 DropDownList。

我需要在我的代码中使用用户在 DropDownList 中选择的值作为 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; 

请您参考如下方法:

您可以使用 try parse 方法。这将确保您的值是一个 int,如果不是,则允许您处理问题而不是抛出异常:

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

您也可以为 Int16 DateTime 等执行此操作。