• 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

    • How can it beat a Steam machine without a serious GPU? The two CU iGPU only provides about 5fps in gaming. That's not going to make any gamer happy.
    • Anthropic introduces Claude Tag, a new AI teammate for Slack by Fiza Ali Anthropic has announced Claude Tag, a new feature that lets teams work with Claude directly inside Slack. The idea is simple: once Claude is added to a Slack workspace and given access to selected channels, users can tag @Claude in conversations and assign tasks. Claude can then work through those requests using connected tools and data sources before posting its results back into a Slack thread. What makes Claude Tag different from a typical chatbot is that it's designed to operate as a shared assistant for an entire team rather than a single user. Everyone in a channel interacts with the same Claude instance. This allows the team members to see ongoing work and continue tasks started by others. Furthermore, Anthropic says the AI can build context over time by following conversations in channels where it has permission to operate. This means users don't have to repeatedly provide the same background information for every request. The system is also designed for asynchronous work. Instead of waiting for responses in a chat window, users can assign a task to Claude and return later once the work is complete. Anthropic says Claude can break larger requests into multiple steps and use connected tools to complete them. Moreover, the system can also schedule follow-up tasks and continue working on projects over extended periods. Another feature allows Claude to keep the users updated and follow up on unresolved tasks when its optional "ambient" mode is enabled. The company says the tool is already being used internally for software development, data analysis, support workflows, and debugging. According to Anthropic, around 65% of its product team's code is now generated through its internal version of Claude Tag. For organisations concerned about security, administrators can control which channels, tools, and data sources Claude can access. Separate Claude instances can also be configured for different departments, helping keep information isolated between teams. Administrators can also monitor activity logs, review completed tasks, and set spending limits at both the organisation and channel level. Claude Tag is now available in beta for Claude Enterprise and Claude Team customers and runs on Claude Opus 4.8 that was announced this May. The feature will also replace Anthropic's existing Claude in Slack application, with current users able to migrate within a 30-day migration window. Lastly, eligible customers will receive introductory credits to help teams evaluate the new experience.
    • Beats Studio Pro wireless over-ear ANC headphones drop to their lowest price yet by Fiza Ali Amazon is currently offering the Beats Studio Pro headphones at their all-time low price. The Studio Pro use 40mm active drivers which are designed to improve clarity and reduce distortion compared to previous models, with up to an 80% improvement over the Beats Studio3 Wireless. A built-in digital processor adjusts frequency response to keep the sound balanced rather than overly boosted in any one area. They also include Active Noise Cancelling that adapts to your surroundings to reduce background noise along with a Transparency mode that lets outside sound in when you need awareness of what’s going on around you. Furthermore, the headphones support personalised Spatial Audio with dynamic head tracking as well as Dolby Atmos playback on supported content. Moreover, built-in voice-targeting microphones improve call quality. You can also switch between three sound profiles including Beats Signature for balanced music playback, Entertainment for films and gaming, and Conversation for clearer voice in calls and podcasts. Physically, they are designed to be worn for long periods without feeling heavy or awkward. The ear cushions use UltraPlush engineered leather while metal sliders allow you to adjust the fit. On the connectivity side, the Studio Pro use Class 1 Bluetooth for a stable, long-range wireless connection. There is also a 3.5mm input if you want to plug in directly, including use with in-flight entertainment systems. Controls are located on the headphones and include a "b" button for music and call control, a volume rocker, and a multifunction button used for switching listening modes, EQ settings, power, and pairing. In addition, the headphones offer integration with both Apple and Android devices. On Apple devices, they support one-touch pairing with iCloud-linked devices, hands-free Siri access, Find My tracking based on last connected location, and automatic software updates. On Android devices, they support Google Fast Pair, Audio Switch between compatible devices, and Google Find My Device tracking, with additional features available through the Beats app. When it comes to the battery performance, it is rated at up to 40 hours of listening time with ANC turned off, and up to 24 hours with ANC or Transparency mode enabled. A 10-minute Fast Fuel charge should provide up to 4 hours of playback. Finally, the headphones use a rechargeable lithium-ion battery and charge via USB-C. Beats Studio Pro Wireless Over-Ear ANC Headphones: $149.95 (Amazon US) Good to know This Amazon deal is U.S. specific, and not available in other regions unless specified. We only use first-party seller links (at the time of article publishing); ensure that you purchase from a first-party seller link only. Check out Today's Deals on Amazon | or our recent tech deals. Become a Prime member (for Students or SNAP) via Neowin Get Prime Access - Prime for half price (for qualifying Medicaid, EBT, SNAP) Subscribe to Prime Video, Audible Plus, Music Unlimited or Kindle Unlimited via Neowin As an Amazon Associate, we earn from qualifying purchases.
    • "lets you pause updates by choosing an end date, for up to 35 days" Wasn't it "indefinitely"?
    • Those extra reboots are related to the UEFI Secure Boot certificate update thing.
  • Recent Achievements

    • Rookie
      DaviKar went up a rank
      Rookie
    • Dedicated
      HidekoYamamoto94 earned a badge
      Dedicated
    • One Month Later
      timbobit earned a badge
      One Month Later
    • One Month Later
      nates earned a badge
      One Month Later
    • Week One Done
      Almohandis earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      460
    2. 2
      +Edouard
      161
    3. 3
      PsYcHoKiLLa
      110
    4. 4
      Michael Scrip
      81
    5. 5
      Steven P.
      69
  • Tell a friend

    Love Neowin? Tell a friend!