im extremely new to c# so im having a little difficulty with the following problem.
below is my following code
int access = 1;
int onlineVideos = 2;
int personalTrainer = 20;
int dietConsultation = 20;
int extras = 0;
if (checkBox1.Checked)
{
extras = access;
}
else if (checkBox2.Checked)
{
extras = onlineVideos;
}
else if (checkBox3.Checked)
{
extras = personalTrainer;
}
else if (checkBox4.Checked)
{
extras = dietConsultation;
}
textBox6.Text = extras.ToString();
i want to be able to easily add the sums of all the boxes that are checked, and then print them to a textbox.
CodePudding user response:
According to your description, you don't need multiple if/else clauses, but only a method which sums all values of your check boxes whose state is checked. Something like this:
foreach (Control c in this.Controls)
{
if((c is CheckBox) && ((CheckBox) c).Checked)
{
yourdecimal = Convert.ToDecimal(c.Text);
}
}
The exact method depends on your exact code, so it might be required to change the "this.Controls" as example. Or it might be necessary to add try/catch to prevent issues if there are non numeric values etc. This is just a way to do this. If you need further assistance, you should please add your source code.
CodePudding user response:
You can simplify the code a bit with a help of ternary operators:
int extras = (checkBox1.Checked ? 0 : access)
(checkBox2.Checked ? 0 : onLineVideos)
(checkBox3.Checked ? 0 : personalTrainer)
(checkBox4.Checked ? 0 : dietConsultation);
A better option is to separate data (options' prices) and logic:
using System.Linq;
...
// Data: option and its price
var prices = new (CheckBox option, int price)[] {
(checkBox1, 1),
(checkBox2, 2),
(checkBox3, 20),
(checkBox4, 20),
};
...
// Logic: we sum all checked options
var extras = prices.Sum(item => item.option.Checked ? item.price : 0);
CodePudding user response:
As an alternative to the solution by @jonas-metzler, you can create a sort-of mapping table (Dictionary
) between checkboxes and their values. This can be used if you're using Text
property on the Checkbox
for something else or as a more general-purpose solution for similar problems outside WinForms.
var checkboxValues = new Dictionary<Checkbox, int>
{
{ checkBox1, access },
{ checkBox2, onlineVideos },
{ checkBox3, personalTrainer },
{ checkBox4, dietConsultation },
};
var sum = checkboxValues.Where(kvPair => kvPair.Key.Checked)
.Sum(kvPair => kvPair.Value);