I am using this calculate function
private void Calculate()
{
double.TryParse(textBox1.Text, out num);
for (int a = 1; a <= 10; a++)
{
listBox1.Items.Add(a + " * " + num + "\n = " + a * num);
}
}
Putting Calculate() inside private void textBox1_TextChanged so it will autocalculate
I am also using :
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
listBox1.Items.Clear();
}
}
This works but if i backspace the value inside textBox1 then when that box is empty it still shows the calculate function using a zero in the calculation displayed inside the listbox as if the empty textbox is a zero if it's empty except when i backspace again it will go away. I was wondering why that is and what the logic is behind that. So to be clear
When i enter 12 the calculate functions show 12, and if i backspace it will be 1 and it will show the calculate function as 1 but if i backspace again to make it empty it will show the calculate function as 0 inside the listbox.Here is the screenshot
Thanks for your time and help.
You don't take the result of TryParse and whatever you have (or not have) in the textbox you run the calculate code. Check if the return of TryParse is false and exit the code
If TryParse is unable to parse the input string (like in case of an empty string) it sets the out variable to its default value (zero for double) and thus you have your code running against the zero multiplier.
This happens also if the user types a not numeric value like a letter.
private void Calculate()
{
if(!double.TryParse(textBox1.Text, out num))
return;
for (int a = 1; a <= 10; a++)
{
listBox1.Items.Add(a + " * " + num + "\n = " + a * num);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments