Thursday, February 10, 2011

Check Items in a CheckedListBox Based on String Tokens/ String Array (C#)


I have been scouring the internet for days looking for ways to check items in a checkedlistbox based on an array of strings.

After finding bits and pieces of the solution, and translating some code from VB.NET, I finally created something that is extremely short, efficient, and completes the job.





            //This code takes a string and splits it up based on a comma delimiter.
            //You can use any kind of string array you want,
            //just be sure that your strings match the items in your list box!
            string[] yourStringArray = yourObject.yourAttribute.Split(',');
          
            //The foreach iteratures through your array.
            foreach (string strToFind in yourStringArray)
            {

                //This code finds the index of the string. It will return -1 if it doesnt find it
                int itemIndex = yourCheckedListBox.FindString(strToFind);

                //This code provides a safe guard in case it cant find your string
                if (itemIndex != -1)
                {
                    //This code will actually 'check' the item at the index specified,
                    //based on the index previously found
                    yourCheckedListBox.SetItemChecked(itemIndex, true);
                }
            }

Applications: If your storing previous checked options as one long string, this is easy code to 'recheck' those items, and is exactly what I'm using it for.
Also, using "Select All ---" type of buttons would be a great application ff you have a LOT of items to choose from and you want to allow a user to check all of a certain type, etc.

No comments:

Post a Comment