Bibu
Bibu

Reputation: 201

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#.

Upvotes: 4

Views: 39943

Answers (6)

Junaid
Junaid

Reputation: 2470

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!!!!!!!!!!

Upvotes: 0

Ravi Ram
Ravi Ram

Reputation: 24488

How about this:

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

Upvotes: 2

Jay
Jay

Reputation: 321

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

Upvotes: 0

Bilal Hashmi
Bilal Hashmi

Reputation: 1485

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.

Upvotes: 0

&#214;zg&#252;r Kara
&#214;zg&#252;r Kara

Reputation: 1333

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());

Upvotes: 3

ABH
ABH

Reputation: 3439

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

Upvotes: 0

Related Questions