• 0

C# Calculating textbox values?


Question

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
}
[/CODE]

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?

Link to comment
https://www.neowin.net/forum/topic/1083591-c-calculating-textbox-values/
Share on other sites

17 answers to this question

Recommended Posts

  • 0

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);
}
[/CODE]

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

[CODE]
TextBox[] m_textboxes;

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

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 :)

  • 0
  On 12/06/2012 at 12:26, mute~ 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.

  • 0

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;)
}
[/CODE]

So your code can look like:

[CODE]
try {
lbl4.Text = string.Format("{0:f0}", txt1.getValue() * txt2.getValue() / 3);
}
catch (Exception) {
MessageBox.Show("WTF
}
[/CODE]

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.

  • 0
  On 12/06/2012 at 15:47, Dr_Asik 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>
[/CODE]

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.

  • 0
  On 12/06/2012 at 15:55, Majesticmerc 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.
  • 0
  On 12/06/2012 at 15:59, Dr_Asik 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.

  • 0

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?

  • 0
  On 14/06/2012 at 07:31, Joni_78 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.

  • 0
  On 14/06/2012 at 13:38, Dr_Asik said:

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.

I meant user needs to enter value 1-5 for every textbox.

  • 0

Ok so you have 8 different calculations that all require 5 inputs for the user and a field to display the result, if I understand correctly. So you could design a UserControl that has 5 input fields and a result field, and use that 8 times with a different equation passed in as a parameter. The equation could be a five-argument Func where the arguments are the 5 different textbox values. Does that make any sense for you?

  • Like 1
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Fully agree with that last sentence. I wasn't able to get the card I wanted at launch, and refuse to play these games with their MSRPs since then. Not a chance I'm going to encourage the price hiking, and I'm fine waiting however long I need to buy a card at the advertised MSRP - for myself however, it's for a 9070 XT... It sucks that lots of people don't do the same, but I get it. I am curious though, in earnest, about your remark about the 9070 XT vs the 5070 Ti - and not to debate or attempt to convince, just genuinely wondering assuming you're speaking of gaming - why do you mention the performance difference between the two being so stark? The 5070 Ti does certainly beat the former in efficiency, but all of the benchmarks I've seen have put them almost equal to each other in performance, with the two more or less trading blows depending on the game, and the overall difference around about 5% in favor of Green. Again, just curious! Not wanting to argue, the assertion was just intriguing to me.
    • I've been thinking about getting a new phone - I'm currently using the Samsung S20+. Looking at a comparison website, I think my only concerns are the resolution and possible sound downgrade. But for that price I think it might be worth trying out.
    • Due to upgrade (PC built in summer 2023). Lian Li O11 Dynamic EVO Black be quiet! Pure Power 12 M 850W ASRock X670E Steel Legend AMD Ryzen 9 7950X3D Boxed G.Skill Trident Z5 Neo RGB F5-6000J2836G16GX2-TZ5NRW NZXT Kraken Elite 360 RGB Zwart 2x Lian Li UNI FAN SL120, 1-pack, Zwart, 120mm 2x Lian Li UNI FAN SL120, 3-pack, Zwart, 120mm Lian Li Universal Vertical Gen4 GPU Riser-kit) MSI GeForce RTX 4070 VENTUS 2X 12G OC WD Black SN850X (no heatsink) 1TB Lexar NM710 2TB M2 Network card Marvell AQC113 10G/5G/2.5G/1000M Current worth to build €2,805 Receipts and original boxes included Notes: Lian Li Universal Vertical Gen4 GPU Riser-kit was bought second-hand SPDIF port cable holder broke (but works) Never been overclocked (except EXPO values) Includes ASRock Thunderbolt 4 AIC in box (not been used due to too few internal USB ports) 2nd Lian Li UNI FAN SL120, 1-pack, Black, 120mm in box (no time to build in rear of case) I am asking €1,800 on a local marketplace in The Netherlands, and although it has been favorited 4x I am only getting lowball offers. It was first listed on May 14. Would I be more successful selling without the video card?
  • Recent Achievements

    • First Post
      brynmot earned a badge
      First Post
    • Reacting Well
      brynmot earned a badge
      Reacting Well
    • Week One Done
      Al_ earned a badge
      Week One Done
    • Week One Done
      MadMung0 earned a badge
      Week One Done
    • Reacting Well
      BlakeBringer earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      478
    2. 2
      +FloatingFatMan
      274
    3. 3
      ATLien_0
      243
    4. 4
      snowy owl
      209
    5. 5
      Edouard
      182
  • Tell a friend

    Love Neowin? Tell a friend!