. Advertisement .
..3..
. Advertisement .
..4..
I’m trying to run a new project. I do a couple of things like this:
namespace MyCalculator
{
public partial class MyForm : Form
{
int n1, n2, n3;
String myResult;
public MyForm()
{
InitializeComponent();
n1 = Int32.Parse(inputField1.Text);
n2 = Int32.Parse(inputField2.Text);
}
private void addBtn_Click(object sender, EventArgs e)
{
addFunc();
calResult();
}
private void subsBtn_Click(object sender, EventArgs e)
{
subsFunct();
calculateResult();
}
private void clrBtn_Click(object sender, EventArgs e)
{
clear();
}
private void addFunc()
{
n3 = n1 + n2;
myResult = Convert.ToString(n3);
}
private void subsFunc()
{
n3 = n1 - n2;
myResult = Convert.ToString(n3);
}
private void calResult()
{
lbl1.Text = myResult;
}
private void clear()
{
lbl1.Text = "";
inputField1.Text = "";
inputField2.Text = "";
}
}
but in my program, I am getting the warning:
Input string was not in a correct format
Can someone explain to me why the issue “the input string was not in a correct format in c#” happened? Where have I gone wrong? Thank you!
You’re trying to convert your Integer value to String but you did not do it properly. Therefore, the Integer value passed to the parse/convert function might not contain a real integer value.
Two things you could do to improve your code:
This was the exact exception I encountered, but it had nothing to do avec parsing numerical inputs. This is not the answer to the OP’s query, but it is acceptable to share the knowledge.
I had declared a string, and was formatting it with JQTree. This requires curly braces ().. To be considered a properly formatted string, you must use doubled curly braces.
This will hopefully help others who are trying to answer this question, but don’t know how to interpret numerical data.
This error indicates that the string from which you are trying to extract an integer is invalid.
It is unlikely that the text boxes contain a valid integer right away when the form is created. This is why you are getting the integer values. It would be much easier to update
n1
orn2
using the button click events, in the same manner as you do in the constructor. You might also want to check out the method. It’s easier to use, even if the string doesn’t actually contain an integer.