Search code examples
c#winformscrystal-reportslistbox

how to identify if multiple indexes are selected from the listbox control in c# winforms?


I am developing an application and I have a requirement to place the fields on front end just like take checkbox. If the user selected particular fields on the checkbox, then based on the selection I will generate crystal report from sql database.

So up to 10 fields checkbox is good enough. But the fields are increased up to 30 and the checkbox count is also increased on the form.

So I decided to take listbox. But in listbox how to identify if multiple items are selected from the user?

In the listbox, I have set SelectionMode property to MultiSimple.

But if I select two or more items, listbox takes only the index of the first item.

Code :

if(listbox1.SelectedIndex==0)
{

 //my code for first field.
}

if(listbox1.SelectedIndex==1)
{

 //my code for second field.
}

Note : I wrote a method for getting a dynamic sql query based on the user selected items. So in my method createSQLquery(), I want to identify the indexes.

I want to identify which items the user has selected from the frontend and based up on that i will proceed to write my code.

Thanks


Solution

  • There are three ways in which you can find
    1)

      foreach (object item in listbox.SelectedItems)
        {
            // do domething
        }
    

    2)

     for (int i = 0; i < ListBox1.Items.Count; i++)
      {
         if (ListBox1.Items[i].Selected)
           {
               // do domething
            }
       }
    

    3)

    var selected = ListBox1.GetSelectedIndices().ToList();
    var selectedValues = (from c in selected
                          select ListBox1.Items[c].Value).ToList();