mouad_raizada
mouad_raizada

Reputation: 27

get checked checkBoxes texts in C#

I have 4 checkBox in my windows form application and I need to get the text of checked checkBox by returning it from a string function but it gives me an exception. The codes of the function are:

string getPerm()
{
   string perm = "";
   foreach(CheckBox chkb in this.Controls)
   {
       if(chkb.Checked==true)
       {
           perm += chkb.Text + ",";
       }
   }
   return perm;
}

And I used this function in Show method of messageBox to show the result on click event of a button , one more problem is that I need to delete the last comma from the result... regards

Upvotes: 0

Views: 1260

Answers (1)

bottaio
bottaio

Reputation: 5093

You can use LINQ to join texts:

return string.Join(",", this.Controls.OfType<CheckBox>.Where(x => x.Checked).Select(x => x.Text));

Your code is not working due to implicit CheckBox cast in the foreach loop. Given that not all of your controls are CheckBoxes (and this is most likely true), the InvalidCastException will pop up. OfType<T> method will make sure that only CheckBoxes will be used in the query.

Additional readings:

Control.Controls

Enumerable.OfType

Upvotes: 3

Related Questions