Welcome Guest! To access all forums & features, please register an account or sign-in. → Why register?



C# Calculating textbox values?


17 replies to this topic - - - - -

#1 Joni_78

    Resident Elite

  • 1,915 posts
  • Joined: 19-April 04
  • Location: Finland

Posted 12 June 2012 - 09:28

Hi,
I have an application with 20 textboxes, i need to do the calculations for example ((TextBox12 * TextBox1 * TextBox7) / 2) and display the result on label when clicking a button.

Ive usually done these like this:

private void lBtn_Click(object sender, EventArgs e)
		{
			double L, L2;
			if (double.TryParse(kTb1.Text, out L) && double.TryParse(kTb2.Text, out L2))
				lBl4.Text = String.Format("{0:f1}", (L2 * L));
			else
				MessageBox.Show("WTF?");
		}

I was wondering if there is better way to do this so that I don't have to add all 20 textboxes into this with && double.TryParse?


#2 +Majesticmerc

    Resident Idealist

  • 5,103 posts
  • Joined: 24-August 05
  • Location: United Kingdom
  • OS: Arch Linux / Win 7
  • Phone: HTC One X

Posted 12 June 2012 - 12:01

You could add the text boxes into an array, and then iterate over the array...

private void lBtn_Click(object sender, EventArgs e) {
	TextBox[] textboxes = {
		kTb1,
		kTb2,
		kTb3,
		...
		kTb20
	};

	double temp = 0D, total = 0D;
	bool isError = false;
	foreach (TextBox tb in textboxes)
	{
		if (!double.TryParse(tb.Text, out temp))
		{
			isError = true;
			break;
		}

		total *= temp
	}

	if (isError)
		MessageBox.Show("WTF?");
	else
	   lBl4.Text = String.Format("{0:f1}", total);
}

To generate the array, you could create it in the form's constructor (or OnLoad event handler), and store it as a class variable...

TextBox[] m_textboxes;

protected void Form1_Load(Object sender, EventArgs e)
{
	TextBox[] m_textboxes = {
		kTb1,
		kTb2,
		kTb3,
		...
		kTb20
	};
}

If the only text boxes on the form are the ones you'll be using in the calculation, you could also use the Controls property to get the list of child text boxes :)

#3 Kami-

    ♫ d(-_-)b ♫

  • 3,624 posts
  • Joined: 28-July 08
  • Location: SandBox

Posted 12 June 2012 - 12:26

I'd put the textboxes into a panel, iterate the panels controls where the type is a textbox, load the value into an object then use the object to output your requirements.

#4 +articuno1au

    Neowinian Senior

  • 3,977 posts
  • Joined: 20-March 11
  • Location: Brisbane, Australia

Posted 12 June 2012 - 12:30

I agree with the panel part, but after that you may as well operate out of the boxes.

#5 Aethec

    Neowinian Senior

  • 2,214 posts
  • Joined: 02-May 10

Posted 12 June 2012 - 12:39

The point of a TextBox is to allow the user to enter text, not numbers.
If you want the user to enter numbers, use NumericUpDowns instead. It'll be much simpler since you are sure they contain numbers :)

#6 +articuno1au

    Neowinian Senior

  • 3,977 posts
  • Joined: 20-March 11
  • Location: Brisbane, Australia

Posted 12 June 2012 - 12:52

Depends on whether he needs doubles or not. Numeric up downs are a pain in the ass with decimals of a sufficient length.

#7 +Majesticmerc

    Resident Idealist

  • 5,103 posts
  • Joined: 24-August 05
  • Location: United Kingdom
  • OS: Arch Linux / Win 7
  • Phone: HTC One X

Posted 12 June 2012 - 14:10

View Postmute~, on 12 June 2012 - 12:26, said:

I'd put the textboxes into a panel, iterate the panels controls where the type is a textbox, load the value into an object then use the object to output your requirements.

Agreed that this is the best way to go.

#8 +Asik

  • 5,970 posts
  • Joined: 26-October 05

Posted 12 June 2012 - 15:47

An application with 20 textboxes sounds like a pain in the ass to begin with. That said, you can at least factor out repetitive code inside methods, for instance you could create an extension method for textboxes to get their value as a double:
public static double getValue(this TextBox txtBox) {
	 return double.Parse(txtBox.Text;)
}
So your code can look like:
try {
	 lbl4.Text = string.Format("{0:f0}", txt1.getValue() * txt2.getValue() / 3);
}
catch (Exception) {
	 MessageBox.Show("WTF?");
}

Btw double.Parse with a try-catch (rather than TryParse) is probably the best approach here, it's not like the cost of throwing an exception in this case was of any significance and it leads to cleaner code.

#9 +Majesticmerc

    Resident Idealist

  • 5,103 posts
  • Joined: 24-August 05
  • Location: United Kingdom
  • OS: Arch Linux / Win 7
  • Phone: HTC One X

Posted 12 June 2012 - 15:55

View PostDr_Asik, on 12 June 2012 - 15:47, said:

An application with 20 textboxes sound like a pain in the ass to begin with. That said, you can at least factor out repetitive code inside methods, for instance you could create an extension method for textboxes to get their value as a double:
<snip>

Btw double.Parse with a try-catch (rather than TryParse) is probably the best approach here, it's not like the cost of throwing an exception in this case was of any significance and it leads to cleaner code.

How does what you did eliminate repetitive code versus simply using a loop? Using an extension method seems a bit overkill.

#10 +Asik

  • 5,970 posts
  • Joined: 26-October 05

Posted 12 June 2012 - 15:59

View PostMajesticmerc, on 12 June 2012 - 15:55, said:

How does what you did eliminate repetitive code versus simply using a loop? Using an extension method seems a bit overkill.
Assuming he's doing some operation that involves getting the values of all textboxes indistinctly (like a sum or an average), a loop is the obvious solution, but from his code example I gathered he wants to do operations involving specific textboxes and is wondering how to avoid having to write the double.TryParse boilerplate every time. Maybe I just misinterpreted though, anyway the loop solution was already given by others here.

#11 +Majesticmerc

    Resident Idealist

  • 5,103 posts
  • Joined: 24-August 05
  • Location: United Kingdom
  • OS: Arch Linux / Win 7
  • Phone: HTC One X

Posted 12 June 2012 - 16:03

View PostDr_Asik, on 12 June 2012 - 15:59, said:

Assuming he's doing some operation that involves getting the values of all textboxes indistinctly (like a sum or an average), a loop is the obvious solution, but from his code example I gathered he wants to do operations involving specific textboxes and is wondering how to avoid having to write the double.TryParse boilerplate every time. Maybe I just misinterpreted though, anyway the loop solution was already given by others here.

Actually yeah I see your point now; the first code snippet in the OP seems to suggest arbitrary calculations while the later code snippets suggest otherwise. Interesting.

#12 OP Joni_78

    Resident Elite

  • 1,915 posts
  • Joined: 19-April 04
  • Location: Finland

Posted 13 June 2012 - 04:38

Actually there will be about 50 textboxes, user inputs value 1-5 and I need to make three calculations from specific textboxes.

#13 ShiZZa

    Neowinian

  • 208 posts
  • Joined: 14-August 02
  • OS: Windows Server 2012
  • Phone: HTC Titian WP7.5

Posted 13 June 2012 - 05:05

I don't recommend looping at all. All values should be read into local vars. Looping is to much magic. Ya looks cool because you wrote like 10 lines of code. But if someone else has to look at it they will call you idiot.

#14 OP Joni_78

    Resident Elite

  • 1,915 posts
  • Joined: 19-April 04
  • Location: Finland

Posted 14 June 2012 - 07:31

I wonder if the textboxes are the right way to do this afterall?

This application will have 50 textboxes and user inputs values 1-5. Two buttons, calculate and clear. After the calculations it shows a the results of 8 calculations and also a graph.

I first thought I do it with popup dialog but then decided to use textboxes so that user can check the entered values but it will have alot of textboxes...

Any ideas?

#15 +Asik

  • 5,970 posts
  • Joined: 26-October 05

Posted 14 June 2012 - 13:38

View PostJoni_78, on 14 June 2012 - 07:31, said:

I wonder if the textboxes are the right way to do this afterall? This application will have 50 textboxes and user inputs values 1-5. Two buttons, calculate and clear. After the calculations it shows a the results of 8 calculations and also a graph. I first thought I do it with popup dialog but then decided to use textboxes so that user can check the entered values but it will have alot of textboxes... Any ideas?
So the user has 5 values to enter and you want to display the result of 8 calculations. Why do you need 50 different fields for that?

I'm not too familiar with Winforms but if you have a lot of data it's usually better to display it with some kind of list control, perhaps DataGrid or ListView.