简体   繁体   English

c#如何在检查多个复选框时在文本框中添加值

[英]c# how to add value in a textbox in checking multiple checkboxes

ok so this is the problem.好的,这就是问题所在。 I tried so many times on using the for loop and the if statement but it doesnt output anything when it comes to the checkbox.我尝试了很多次使用 for 循环和 if 语句,但是当涉及到复选框时它没有输出任何内容。 My question is does this really work?我的问题是这真的有效吗? i derived some parts of my code to the other answers in updating multiple checkboxes but i dont think it works我在更新多个复选框时将代码的某些部分导出到其他答案,但我认为它不起作用

foreach (var control in this.Controls)
{
    if (control is CheckBox)
    {
        if (ffcheck.Checked)
        {
            InitAmo = InitAmo + 50;
            InitAmE.Text = "P" + InitAmo.ToString() + ".00";
        }
    }
}

and an additional question too.还有一个额外的问题。 If ever the code you post does work, can it work and update the total amount if ever i clicked multiple check boxes?如果您发布的代码确实有效,如果我单击多个复选框,它是否可以工作并更新总金额? can you also please specify the logic that you use in order to derive to that answer and if ever that another set of code have more functionality and reduce the storage needed to run this code can you please specify it.您能否还请指定您使用的逻辑以得出该答案,如果另一组代码具有更多功能并减少运行此代码所需的存储空间,请指定它。 Thank you very much for your time to answer this code非常感谢您花时间回答此代码

The problem with your current solution is that, while you correctly perform the type test on each control, your subsequent check for .Checked is not performed on that control.您当前解决方案的问题在于,虽然您正确地对每个控件执行了类型测试, .Checked不会对该控件执行对.Checked的后续检查。

Regardless, your solution can be greatly simplified无论如何,您的解决方案可以大大简化

InitAmo = this.Controls
    .OfType<CheckBox>()
    .Count(checkbox => checkbox.Checked) * 50;

InitAmE.Text = $"{InitAmo: P 0.00}";

This filters the controls to only those that are CheckBox instances, counts the ones that are Checked , and multiplies that quantity by 50. It then formats the result to 2 decimal places of precision.这将控件过滤为仅那些CheckBox实例,计算Checked实例,并将该数量乘以 50。然后将结果格式化为 2 个小数位精度。

You can try this:你可以试试这个:

foreach (var control in this.Controls)
{
    if (control is CheckBox)
    {
        if (ffcheck.Checked)
        {
            int TextboxValue = int.Parse(InitAmo.Text);
            TextboxValue = TextboxValue + 50;
            string NewValue = TextboxValue.ToString();
            InitAmo.Text = "P" + NewValue + ".00";
        }
    }
}

Basically what I did is I did the conversions from string to int and back to str before I displayed the result.基本上我所做的是在显示结果之前进行了从字符串到 int 再到 str 的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM