• 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

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

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

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

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

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

    • State of Decay 2, Blasphemous 2, and more join Xbox Free Play Days by Pulasthi Ariyasinghe The latest Free Play Days offer has just kicked off, giving Xbox players the chance to try out a new selection of games over the weekend. The offerings this time aren't as massive as last weekend, but there are still major releases for Xbox players to jump into. This includes Undead Labs' post-apocalyptic title State of Decay 2, as well as two Team17-published titles. Two of the games being offered this time are available to all Xbox players without needing any kind of Game Pass subscription. In the fully free-to-play section, you can jump into State of Decay 2. The title is both an action survival title and a community builder, letting players choose a map, set up their base, and try to keep the growing zombie threat at bay. Cooperative play is available too. Don't forget that the studio is preparing a third entry for 2027. Next, Blasphemous 2 drops in for Metroidvania and Soulslike fans, where The Penitent One returns for another adventure. The title has tough combat with multiple weapon options, deadly traps to avoid, and platforming sequences requiring a lot of patience and timing. Keep in mind though that the offer does have a 5-hour time limit attached to it. Lastly, Xbox Game Pass Ultimate, Premium, and Essential members can now try out the WWII-set first-person shooter Hell Let Loose. The multiplayer game offers 50 vs 50 combat in massive maps, with infantry, tank, and artillery options available for players. Here are the announced games and the platforms they are available to play on: Hell Let Loose (Xbox Series X|S, PC) State of Decay 2: Juggernaut Edition (Xbox Series X|S, PC) Blasphemous 2 (Xbox Series X|S, Xbox One) To easily find the titles on Xbox consoles, first head to the Store, and then in the sidebar, find the Home section. In there, open the Subscriptions tab. The Free Play Days collection will show up in this area. This week's Free Play Days promotions will end on Sunday, June 11, at 11:59 pm PT.
    • Can we not have paperless office, like we was promised in the 80's
    • I actually laughed out loud in real life at the heading on this—whatever Microsoft is drinking, I want some of it.
    • Euro-Office must default to ODF to be considered "genuinely European", LibreOffice argues by David Uzondu Euro-Office is a web-based collaborative office suite that positions itself as a "European sovereign alternative" to American tech companies, backed by a coalition of developers including Nextcloud, IONOS, Abilian, BTactic, OpenProject, and, more recently, Tuta. The project officially went live a couple of days ago, but not before drawing heavy fire from LibreOffice developers, who called the marketing claim that Euro-Office represents the "first open-source office suite developed in Europe" a deceptive historical inaccuracy because projects like OpenOffice and LibreOffice existed decades earlier. Now that the project has launched, LibreOffice is back with another complaint, arguing that Euro-Office cannot consider itself "genuinely European" while it pushes proprietary Microsoft defaults on users. Euro-Office had promised to improve the OpenDocument Format (ODF) back in April, but the current release still plagues users with several technical failures. For instance, the suite lacks an admin setting to enforce ODF, and mobile editors completely block ODF saves, forcing files into Microsoft's OOXML formats. Some configurations force files into read-only mode, while editing frequently corrupts document formatting or erases data. LibreOffice thinks that merely supporting a format as an afterthought does not make you a sovereign alternative, as file formats are the battleground where" digital sovereignty is won or lost." The road to the first stable release of Euro-Office has been quite bumpy due to an aggressive public fallout with OnlyOffice, from which the coalition originally forked the project. OnlyOffice struck back by accusing the coalition of violating copyright terms under its AGPLv3 branding requirements by stripping the original branding anyway and forking the code. Getting Euro-Office up and running is a bit wonky (at least for non-technical users), as there is no direct installer to grab off the web. The easiest way we learnt is by using Docker. First, pull the official Euro-Office image from the GitHub Container Registry: docker pull ghcr.io/euro-office/documentserver:latest Then, run the container with active ports and a secure JWT token, enabling the test environment: docker run -i -t -d -p 8080:80 --restart=always -e EXAMPLE_ENABLED=true -e JWT_SECRET=my_secure_jwt_secret ghcr.io/euro-office/documentserver:latest And finally, open a web browser and go to the following address: http://localhost:8080 If you are running this on a remote server, replace localhost with your server's IP address. You will see the Euro-Office test page, where you can create new text documents, spreadsheets, or presentations directly in the browser. Image via Euro-Office Nextcloud promises that proper standalone desktop versions and mobile apps will arrive in a future release.
  • Popular Contributors

    1. 1
      +primortal
      486
    2. 2
      PsYcHoKiLLa
      197
    3. 3
      +Edouard
      155
    4. 4
      Steven P.
      83
    5. 5
      ATLien_0
      69
  • Tell a friend

    Love Neowin? Tell a friend!