Amit
Amit

Reputation: 129

Multiple buttons in a one event handler not working

Below is the okButton_Click function where I am trying to add multiple buttons. I am getting error

input string was not in a correct format

I have read other solutions regarding similar questions but still but I am having trouble fixing the code below. Any help would be appreciated.

Forgot to mention earlier that both buttons on individual basis work. Meaning, if I comment the first button, the second one works and vice versa.

protected void okButton_Click(object sender, EventArgs e)
{   
    Button button = (Button)sender;

    // button info <asp:Button ID="triangleAreaButton" runat="server" Text="Calculate"
    // OnClick="okButton_Click" CssClass="btn btn-success" />
    triangleAreaResultLabel.Text = button.ID;
    TriangleProperties triangle =
        new TriangleProperties(int.Parse(baseTextBox.Text), int.Parse(heightTextBox.Text));
    triangleAreaResultLabel.Text = String.Format("({0} x {1}) / 2  = {2}", baseTextBox.Text,
        heightTextBox.Text, triangle.AreaOfTriangle().ToString());

    // button info <asp:Button ID="pythagorasTheoremButton" runat="server" Text="Calculate"
    // OnClick="okButton_Click" CssClass="btn btn-success" />
    hypotenuseLabelforPyT.Text = button.ID;
    TriangleProperties pythagorasTheorem =
        new TriangleProperties(int.Parse(heightTextBoxforPyT.Text),
            int.Parse(baseTextBoxforPyT.Text), 0);
    hypotenuseLabelforPyT.Text =
        String.Format("{0} ", pythagorasTheorem.PythagorasTheoremFindHypotenuse().ToString());
}

Upvotes: 0

Views: 78

Answers (1)

Sach
Sach

Reputation: 10393

So this line gives you the error.

TriangleProperties pythagorasTheorem = new TriangleProperties(
        int.Parse(heightTextBoxforPyT.Text),
        int.Parse(baseTextBoxforPyT.Text), 
        0);

Take a look at the int.Parse() method documentation.

Under the exceptions this method may generate:

FormatException : s is not in the correct format.

So, the actual text in either of the text boxes is not a valid integer. Even if you have a white space at the end, like a space or a tab, that still won't work and will give you this error.

Instead of int.Parse() you should use int.TryParse(), which will check if the conversion is possible, and will return true if so, and will return false if not possible. In the case of a valid conversion the out parameter will contain the converted value.

So your code should look something like:

if(int.TryParse(heightTextBoxforPyT.Text, out int heightVal) && 
   int.TryParse(baseTextBoxforPyT.Text, out int baseVal))
{
    TriangleProperties pythagorasTheorem = new TriangleProperties(heightVal, baseVal, 0);
}
else
{
    // Perhaps output an error message
}

Upvotes: 2

Related Questions