• 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

    • It’s not desperation, it’s marketing. Companies do that…
    • Some AMD Ryzen users can get free Windows performance boost with this simple system tweak by Sayan Sen AMD understands that there is a lot of demand for its X3D processors and for good reason too, since they offer some of the best gaming experiences. As such, the company plans to launch a new 6-core Ryzen 5 9600X3D for those who may not want to spend top dollar on a 9800X3D. What makes X3D special is the densely packed last level cache (LLC) wherein the L3 (level 3) cache is 3D die-stacked such that there is a whole lot of it that the cores can access on demand all within the smallest footprint. This is said to help with latency especially, and games happen to be quite sensitive to it since they are a mixed workload and so there is a lot of to-and-fro. However, despite that fact, users have noticed micro-stuttering and freezes on Ryzen X3D CPUs. Although there is no official fix, some of the affected users have managed to resolve the issues by tweaking a motherboard setting. The tweak is related to a setting called "GLOBAL C-STATE CONTROL" (it may be called something else by your motherboard vendor) and changing it to 'Enabled' from 'Auto' could fix stuttering and lag-related issues in games. If you are not familiar with them, Processor Power Management is done through Advanced Configuration and Power Interface (ACPI) P-states or C-states. While P-states or performance states handle CPU voltage-frequency scaling, C-states deal with CPU sleep states so that some of the CPU functions, which are not necessary at that moment, are disabled. The P-states and C-states work together to make the processor run more efficiently. It helps the OS and apps determine which cores can be parked. The Global C-state control setting helps users manage not only the DF and CPU core C-states but also the I/O C-states too. For those wondering, DF here refers to Data Fabric or AMD's high bandwidth Infinity Fabric interconnect between CPUs, GPUs, and more, on AMD systems. By default, this is set to "Auto" which also means that it is "Enabled" by default. However, in the case of X3D parts, Auto may set this setting to "Disabled" and thus manually toggling it to "Enabled" may be necessary. X3D processors, the dual CCD (core complex die) ones especially, have their V-cache on a single CCD. If the CPPC (Collaborative Processor Performance Control), which lets an OS like Windows control the "preferred core" and clock speed boost, isn't working optimally to assign the correct gaming CCD, then this fix could well work. Global C-State Auto: Global C-State Enabled: We ran a benchmark on our Ryzen 9 9950X3D to see if toggling the settings would make a difference, and well, it didn't in the case of AIDA64. However, since this is a synthetic test that measures cache and memory exclusively, we can't definitively conclude that the fix will also not make a difference in the case of games. Another remedy for stuttering is to disable the monitoring of the "Power percent" metric on MSI Afterburner if you have it on. This has been a long-known issue and in fact can help you even if you are not using an X3D CPU. Source: Reddit (link1, link2) via YouTube
    • I only have one contact on WhatsApp. And that contact has sms also. I have many more contacts that use WhatsApp also, but everyone defaults to use iMessage, SMS or RCS anyway. Not a loss for me. I'm in Norway where mostly nobody uses WhatsApp.
    • Apple is boring for a kid. Only fun is browsing websites for HTML games. A PC with steam is another story. Of course if the child plays video games all day then maybe that might not be a good idea. :-)
    • Looking for a specific setting in Settings? Sorry, the option just doesn’t exist as you’d need to elevate for that. Want to do something quickly and efficiently? Nah, forced to use a “modern” interface which takes far longer to achieve what you’re looking to do. (Example: disable a NIC)
  • Recent Achievements

    • One Month Later
      DecaffKnight94 earned a badge
      One Month Later
    • Dedicated
      S.P earned a badge
      Dedicated
    • One Month Later
      adxnksd42031 earned a badge
      One Month Later
    • Rising Star
      aphanic went up a rank
      Rising Star
    • Contributor
      GravityDead went up a rank
      Contributor
  • Popular Contributors

    1. 1
      +primortal
      663
    2. 2
      ATLien_0
      261
    3. 3
      Michael Scrip
      234
    4. 4
      Steven P.
      159
    5. 5
      +FloatingFatMan
      151
  • Tell a friend

    Love Neowin? Tell a friend!