• 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

    • "productivity purposes and actual work"? That totally depends on the productivity and the actual work. Many people can't switch to Linux simply because their actual work requires software and workflows that aren't available/possible on Linux. Also, if you're a non-casual gamer, stay away from Linux. Yes, it has improved a lot on the gaming side of things, but it still can't beat Windows on compatibility. You can expect every game on the market to just work on Windows from day one, the same can't be said about Linux. Games are designed specifically for Windows, after all, and Proton isn't perfect.
    • Well, that's good to hear. No one here wants MAGAs to breed.
    • OpenAI announces significant updates to Codex and voice agent tools by Pradeep Viswanathan Apart from serving the ChatGPT experience to hundreds of millions of users everyday, OpenAI is also engaged in providing its platform for developers creating AI applications. OpenAI is popular among developers not just for its cutting-edge models, but also because of its strong tooling and support for developers. Today, OpenAI announced two significant updates for developers. The first is about Codex, OpenAI’s software engineering agent. OpenAI is now making Codex available to ChatGPT Plus users. For a limited time, ChatGPT Plus users will be able to enjoy generous usage limits, but OpenAI will rate-limit them during high-demand periods. Codex can now connect to the internet to install dependencies, upgrade packages, run tests that need external resources, and more. OpenAI specified that internet access is off by default, but users can enable it for specific environments. Users can also control the specific domains which Codex can access and more. This Codex Internet access capability is available for ChatGPT Plus, Pro, and Teams users, and it is coming soon to Enterprise users. With today’s update, Codex users can now update existing pull requests when following up on a task. Finally, users can now dictate tasks to Codex. Apart from the above and bug fixes, OpenAI has made the following improvements to Codex: Added support for binary files: When applying patches, all file operations are supported. When using PRs, only deleting or renaming binary files is supported for now. Improved error messages for setup scripts. Increased the limit on task diffs from 1 MB to 5 MB. Increased the limit for setup script duration from 5 to 10 minutes. Polished GitHub connection flow. Re-enabled Live Activities on iOS after resolving an issue with missed notifications. Removed the mandatory two-factor authentication requirement for users using SSO or social logins. The second major update from OpenAI today is about voice agents. OpenAI’s Agents SDK is now available in TypeScript and it comes with support for handoffs, guardrails, tracing, MCP, and other core agent primitives. This SDK also includes new support for human-in-the-loop approvals, allowing developers to pause tool execution, serialize and store the agent state, approve or reject specific calls, and resume the agent run. OpenAI also released an updated speech-to-speech model with improvements in instruction-following reliability, tool-calling consistency, and interruption behavior. Also, developers can now customize how fast the voice speaks during each session. Developers can now access the updated model via gpt-4o-realtime-preview-2025-06-03 in the Realtime API and gpt-4o-audio-preview-2025-06-03 in the Chat Completions API. Finally, the Traces dashboard now supports Realtime API sessions, allowing developers to easily visualize voice agent runs, including audio input/output, tool invocations, and interruptions.
    • VirtualBox 7.1.10 by Razvan Serea VirtualBox is a powerful x86 and AMD64/Intel64 virtualization product for enterprise as well as home use. Targeted at server, desktop and embedded use, it is now the only professional-quality virtualization solution that is also Open Source Software. Presently, VirtualBox runs on Windows, Linux, macOS, and Solaris hosts and supports a large number of guest operating systems including but not limited to Windows (NT 4.0, 2000, XP, Server 2003, Vista, 7, 8, Windows 10 and Windows 11), DOS/Windows 3.x, Linux (2.4, 2.6, 3.x, 4.x, 5.x and 6.x), Solaris and OpenSolaris, OS/2, OpenBSD, NetBSD and FreeBSD. Some of the features of VirtualBox are: Modularity. VirtualBox has an extremely modular design with well-defined internal programming interfaces and a client/server design. This makes it easy to control it from several interfaces at once: for example, you can start a virtual machine in a typical virtual machine GUI and then control that machine from the command line, or possibly remotely. VirtualBox also comes with a full Software Development Kit: even though it is Open Source Software, you don't have to hack the source to write a new interface for VirtualBox. Virtual machine descriptions in XML. The configuration settings of virtual machines are stored entirely in XML and are independent of the local machines. Virtual machine definitions can therefore easily be ported to other computers. VirtualBox 7.1.10 changelog: VBoxManage: Fixed a crash when running 'guestcontrol run' on Windows hosts (bug #22175) Audio: Fixed device switching on Windows hosts (bug #22267) Windows host installer: Fixed multiple installation entries in the 'Add or remove programs' dialog and upgrade issues Linux host: Fixed issue which caused VM Selector process crash due to missing libdl.so and libpthread.so libraries (bug #22193) Linux host: Removed libIDL as a build time dependency when building VirtualBox from source code (bug #21169) Linux guest and host: Added initial support for kernel 6.15 (bug #22420) Linux guest: Added initial support for kernel 6.16-RC0 Linux guest and host: Fixed issue with building modules for UEK8 kernel on Oracle Linux 9 distribution RDP: Fixed issue when it was not possible to paste clipboard buffer into a guest over RDP remote session Download: VirtualBox 7.1.10 | 119.0 MB (Open Source) Download: VirtualBox 7.1.10 Extension Pack | 21.9 MB View: VirtualBox Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      jrromero17 earned a badge
      Week One Done
    • One Month Later
      jrromero17 earned a badge
      One Month Later
    • Conversation Starter
      johnwin1 earned a badge
      Conversation Starter
    • One Month Later
      Marwin earned a badge
      One Month Later
    • One Year In
      fred8615 earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      237
    2. 2
      snowy owl
      156
    3. 3
      ATLien_0
      140
    4. 4
      Xenon
      131
    5. 5
      +FloatingFatMan
      130
  • Tell a friend

    Love Neowin? Tell a friend!