Reputation: 49
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. 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
Upvotes: 1
Views: 825
Reputation: 51
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.
Upvotes: 0
Reputation: 31873
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.
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.
Upvotes: 1