Search code examples
c#.netformsparsingtextbox

Input string was not in a correct format, Textbox from another Form


This might be a duplicate but i haven't found anyone with the exact same issue as me so thats why i made a post. I get the 'Input string was not in a correct format' error when ever i try to convert textbox text to int. To get the text from input textbox:

public void textBoxValue1_TextChanged(object sender, EventArgs e)
    {
        var textBoxValue1Text = sender as TextBox;
        string textBoxValue1ConvertedText = 
        System.Convert.ToString(textBoxValue1Text);
        value1txt = textBoxValue1ConvertedText;
    }

And to convert it:

string search1value = FormParameters.value1txt;
int search1ValueInt = int.Parse(FormParameters.value1txt); // Error occurs here

What am i doing wrong? Thanks in advance


Solution

  • The problem is in this method

    public void textBoxValue1_TextChanged(object sender, EventArgs e)
    {
        var textBoxValue1Text = sender as TextBox;
        string textBoxValue1ConvertedText = System.Convert.ToString(textBoxValue1Text);
        value1txt = textBoxValue1ConvertedText;
    }
    

    textBoxValue1Text is not the text of the TextBox; it is the Textbox itself.

    Use

    string textBoxValue1ConvertedText = System.Convert.ToString(textBoxValue1Text.Text);
    

    instead.

    When you convert the TextBox to string you're calling the .ToString() of the TextBox and not the value of the Text property.