Retrieve String from Checked Items in a ListView Control

LevyDee 0 Tallied Votes 2K Views Share

Hi guys, I just thought I would add this because it was a pain for me to muster up
due to the lack of information through google and msdn on the topic. Enjoy =)

private void Button1_Click(object sender, EventArgs e)
        {    
            ///////////////////////////////////////////Retrieve total number of Checked Boxes
            int i = listView1.CheckedItems.Count;
            string []sTemp = new string[i];

            ListView.CheckedIndexCollection k = listView1.CheckedIndices;//////////Retrieve Index number of boxes that are Checked

            for (int n = 0; n < listView1.CheckedItems.Count; n++)
            {
                sTemp[n] = listView1.Items[k[n]].Text; //////////Cycle through index numbers of Checked processes and add to string array                           

            }
        }
Geekitygeek 480 Nearly a Posting Virtuoso

Handy code. I would make one small suggestion though.
Rather than retrieving the CheckedIndexCollection and nesting it, you can make the code much more readable by using a foreach loop:

int n = 0;
    foreach (ListViewItem item in listView1.CheckedItems)
    {
        sTemp[n] = item.Text;
        n++;
    }

I've added a fresh counter for the sTemp index but you could reset 'i' to zero and reuse it, or alternatively use a List<string> so you can add items without having to set its size initially:

List<string> sTemp = new List<string>();
sTemp.Add("a");
sTemp.Add("b");
LevyDee 2 Posting Whiz in Training

Ohh, that would make sense. Also sorry, I just moved over to c# from c++ 2 days ago. I havent learned the foreach yet =(

Geekitygeek 480 Nearly a Posting Virtuoso

No need to apologise, thats what we're all here for - to teach each other :)
It wasnt a critisism, just an observation. If you are new then i would definitely recommend looking up the syntax on msdn. A foreach loop can iterate through any collection that implements IEnumerable.
Also, check out the generic List<T> while you're there. Very handy collection to get to grips with :)

LevyDee 2 Posting Whiz in Training

Well, I am aware of STL classes and working with templates, but do they work the same way in c# as in c++?

Geekitygeek 480 Nearly a Posting Virtuoso

Having never worked with C++ i can't say with any certainty; however, having had a quick read through some STL info, it appears they work in much the same way as Collections and Gerneic Collections in C#.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.