Convert selected value from dropdown to int

I have a dropdown and I want the selected value to be put into an int variable and then in my aspx page I want to assign it to the rowspan. This is my C # code to get the value and convert it:

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

      

And this is my aspx code where I am trying to assign a variable a:

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

      

I am getting the error: I cannot create an object of type int32 from its string representation. Can anyone tell why? This is an asp.net application from C #.

+3


source to share


6 answers


try setting this value when you read the 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());

      

+2


source


How about this:



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

      

+2


source


If the value is drop.SelectedValue

not equal int

, you will get this error. For example, if the value contains a floating point.

0


source


Try using int.Parse(drop.SelectedValue)

or int.Parse(drop.SelectedValue.Trim())

instead Int32.Parse(drop.SelectedValue.ToString())

. drop.SelectedValue

is already in string format so you don't need to convert it withToString

0


source


Try a Int32.TryParse

method that tries to convert the string representation to int without throwing an exception. Also check the values ​​of the dropdowns. This exception is thrown when the string value does not represent an integer value.

0


source


if the dropdown is in numbers (numbers) 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 just do this ...

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

      

It always works for me !!!!!!!!!!

0


source







All Articles