0
votes

I have different checkboxes in vb.net webform with different text ...

checkbox1.text=100
checkbox2.text=300
checkbox3.text=550 and so on .....

i want when i check checkbox1 and checkbox2 then in textbox1 the text would be 400

means as many as checkbox i select the sun of checkboxes selected will be calculated in textbox using VB.NET ....

i m using Visual Studio 2008

2

2 Answers

1
votes

If you are looking at server side code then following code should do the trick:

private int mTotal;

private void EnumerateCheckBoxes(Control control)
{
   if (control is CheckBox)
   {
     var check = (CheckBox)control;
     if (check.Checked)
     {
        int value;
        if (int.TryParse(check.Text, out value))
        {
          mTotal += value;
        }
     }
   }
   else if (control.HasControls())
   {
     foreach(var c in control.Controls) 
     {
       EnumerateCheckBoxes(c);
     }
   }
}

protected void Page_Load(Object sender, EventArgs e)
{
   mTotal = 0;
   EnumerateCheckBoxes(this.Form);
   textbox1.Text = mTotal.ToString();
}

Although, this is in C#, it should be easy to port to VB.NET. Also few other things to consider:

  1. This code will count radio buttons as well as because it gets inherited from CheckBox. If that is to be avoided then replace if (control is CheckBox) with if (control.GetType() == typeof(CheckBox))
  2. If you wish to consider checkboxes from CheckBoxList then you have to write another condition to see if control is CheckBoxList and then within condition, enumerate items withing checkboxlist. Items count to be added to total count while selected items to be added to checked count.
0
votes

Use a hidden field and a bit of javascript to set the value, bind this event when a checkbox is checked

function UpdateValue(){
var total= 0;
$('input:checkbox:checked').each(function (i) {
    val = total+ int.parse(this.value); //or html
});
   $('#hiddenValField').html(total) ;
}