Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected Checkbox from a bunch of checkboxes in .c#.net

Tags:

c#

.net

winforms

The problem is faced under c# .NET, Visual Studio, Windows Form Application

I have a bunch of checkboxes placed randomly in one form and in one panel. So, If any checkbox is selected in the form its value is supposed to be added up.

Bottomline: Instead of using plenty of "If-else loops", to evaluate whether its been checked or not. I wanna simplify it using a "for loop ".

Is there any Checkbox group name type feature, which I can use???

I wanna code something like this:

for(int i=0;i<checkboxes.length;i++)
{
    string str;
    if(chkbox.checked)
    {
        str+=chkbox.value;
    }
}

Where checkboxes is a group name.

like image 633
SALZZZ Avatar asked Dec 12 '12 08:12

SALZZZ


2 Answers

You can use a simple LINQ query

var checked_boxes = yourControl.Controls.OfType<CheckBox>().Where(c => c.Checked);

where yourControl is the control containing your checkboxes.


checked_boxes is now an object which implements IEnumerable<CheckBox> that represents the query. Usually you want to iterate over this query with an foreach loop:

foreach(CheckBox cbx in checked_boxes) 
{
}

You also can convert this query to a list (List<Checkbox>) by calling .ToList(), either on checked_boxes or directly after the Where(...).


Since you want to concatenate the Text of the checkboxes to a single string, you could use String.Join.

var checked_texts = yourControl.Controls.OfType<CheckBox>()
                                        .Where(c => c.Checked)
                                        .OrderBy(c => c.Text)
                                        .Select(c => c.Text);

var allCheckedAsString = String.Join("", checked_texts);

I also added an OrderBy clause to ensure the checkboxes are sorted by their Text.

like image 155
sloth Avatar answered Nov 15 '22 21:11

sloth


CheckBox[] box = new CheckBox[4];  

box[0] = checkBox1;  
box[1] = checkBox2;  
box[2] = checkBox3;  
box[3] = checkBox4;

for(int i=0; i<box.length; i++)
{
      string str;
      if(box[i].checked== true)
      {
           str += i.value;
      }
} 

I think this code will work with DotNet4.0. Plz let me know any error occurs. Treat 'box' as regular array.

like image 43
AkshayP Avatar answered Nov 15 '22 20:11

AkshayP