SURESH MOGUDALA
SURESH MOGUDALA

Reputation: 35

how to pass textbox values to a method in c#.net for windows forms application

class test
{
    public void read()
    {
       int a=convert.toint32(textbox1.text);
    }
}

Error shows that String format is not correct Can any one solve this....

Upvotes: 1

Views: 1679

Answers (3)

iabbott
iabbott

Reputation: 881

Use Int32.TryParse to make sure the value in textbox1 is convertable into int

class test
{
    public void read()
    {
       int a = 0;
       if(Int32.TryParse(textbox1.Text, out a))
       {
           // a is the integer from the textbox
       }
       else
       {
           MessageBox.Show("The textbox does not contain a number!");
       }
    }
}

Upvotes: 1

DGibbs
DGibbs

Reputation: 14618

The error is probably because the text value of textbox1.Text1 cannot be converted to an int.

You might want to consider using Int32.TryParse():

public void read() 
{ 
    int val = 0;
    if(Int32.TryParse(textbox1.Text, out val))
    {
        //parse was successful
    }
    else
    {
        MessageBox.Show("Input string cannot be parsed to an integer");
    }
} 

That way, if the parsing fails you can handle it yourself either by displaying an error message as in my example or throwing the exception.

Upvotes: 0

Tomzan
Tomzan

Reputation: 2818

It means that the value of textbox1.text is not integer.

Upvotes: 0

Related Questions