简体   繁体   中英

converting selected value from dropdownlist into int

I have a drop down list and I want the selected value to put into an int variable, then in my aspx page I want to assign it to a rowspan. This is my C# code for getting the value and converting it:

protected void drop_SelectedIndexChanged(object sender, EventArgs e)
        {
            int a = Int32.Parse(drop.SelectedValue.ToString());

And this is my aspx code where I'm trying to assign the variable a :

 <asp:TableHeaderRow>
 <asp:TableHeaderCell RowSpan="<% a %>">Hostese</asp:TableHeaderCell>
 </asp:TableHeaderRow>  

I get the error: cannot create an object of type int32 from its string representation. Can anyone say why? It's an asp.net application with C#.

这个怎么样:

int a = int.TryParse(drop.SelectedValue, out a)? a : 0;

try setting this value when you read dropdown value.

<asp:TableHeaderRow>
    <asp:TableHeaderCell ID="h1" >Hostese</asp:TableHeaderCell>
</asp:TableHeaderRow> 



protected void drop_SelectedIndexChanged(object sender, EventArgs e)
{
    h1.RowSpan = Int32.Parse(drop.SelectedValue.ToString());

if dropdown list items value is in numbers(digits) like...

    <asp:DropDownList ID="DropDownList1" runat="server">
         <asp:ListItem Text="Please Select" Value="-1"></asp:ListItem>
         <asp:ListItem Text="1st" Value="1"></asp:ListItem>
         <asp:ListItem Text="2nd" Value="2"></asp:ListItem>
         <asp:ListItem Text="3rd" Value="3"></asp:ListItem>
     </asp:DropDownList>

then you can simply do this...

int i = Int32.Parse(DropDownList1.SelectedValue);

This always works for me!!!!!!!!!!

If value of drop.SelectedValue isn't int then you will get this error. For example if the value contains a floating point.

Try using int.Parse(drop.SelectedValue) or int.Parse(drop.SelectedValue.Trim()) instead of Int32.Parse(drop.SelectedValue.ToString()) . drop.SelectedValue is already in string format so you need not convert it using ToString

Try Int32.TryParse method, which try to convert string representation to int without throwing an exception. Also check the values of your drop down list items. This exception occurs when string value does not represent integer value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM