想知道如何轻松从复选框中添加总和
我是C#的新手,所以我在以下问题上遇到了一些困难。
以下是我以下代码,
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();
我希望能够轻松地添加所检查的所有框的总和,然后将其打印到文本框中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据您的描述,您不需要多个if/否则子句,而只需总和检查状态的所有复选框的所有值。类似的内容:
确切的方法取决于您的确切代码,因此可能需要更改“ This.controls”为例。否则可能有必要添加尝试/捕获以防止问题等问题等。这只是做到这一点的一种方法。如果您需要进一步的帮助,请添加您的源代码。
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:
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.
您可以借助三元运营商的帮助来简化代码:
一个更好的选择是 ext data(选项价格)和逻辑:
You can simplify the code a bit with a help of ternary operators:
A better option is to separate data (options' prices) and logic:
作为 @jonas-metzler的解决方案的替代方法,您可以在复选框及其值之间创建一种映射表(
字典
)。如果您使用text
在复选框上使用
属性的属性,则可以使用此功能,也可以用作其他问题的更通用解决方案。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 usingText
property on theCheckbox
for something else or as a more general-purpose solution for similar problems outside WinForms.