Search code examples
c#windows-phone-7listpicker

How to get multiple selected items from ListPicker and display them in MessageBox


Here is my code for the list of the items in a ListPicker. What I am trying to do is select one or more options and then after I press submit button I would like to display a MessageBox with the selected Items separated by commas. I also would like to store this value of the items selected to the database but, the first I am trying to do is populate the data into MessageBox.

                lstPickerType.Items.Add("Aircrafts");
                lstPickerType.Items.Add("Boats");
                lstPickerType.Items.Add("Cars");
                lstPickerType.Items.Add("Helicopters");
                lstPickerType.Items.Add("Electric Powered");
                lstPickerType.Items.Add("Gas Powered");

Here is the code that I have got to create a string from the list that is then displayed when the ListPicker is collapsed.

private void lstPickerType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

    lstPickerType.SummaryForSelectedItemsDelegate = SummarizeItems;

}

private string SummarizeItems(IList items)
{
    if (items != null && items.Count > 0)
    {
        string summarizedString = "";
        for (int i = 0; i < items.Count; i++)
        {
            summarizedString += (string)items[i];

            // if the item is not last coma is added
            if (i != items.Count - 1)
                summarizedString += ", ";
        }
        return summarizedString;

    }
    else
        return "Nothing selected";
}

Finally for the button to display the MessageBox i have following code.

private void btnAddLocation_Click(object sender, RoutedEventArgs e)
        {

            foreach (var item in this.lstPickerType.SelectedItems)
            {
                var items = new List<object>();
                MessageBox.Show(items.ToString());

            }

I would really appreciate if anyone could help me to solve this issue. Thank You.


Solution

  • I'm a bit rusty of C#, and i don't have visual studio in this pc, but I would achieve your result without the selectionchanged event in the listpicker.

    Trythis code in the button click: Edit: a cast was missing.

    private void btnAddLocation_Click(object sender, RoutedEventArgs e)
    {
        string r = "";
        for (int i=0; i<this.lstPickerType.SelectedItems.Count; i++)
        {
            r += ((ListPickerItem)this.lstPickerType.SelectedItems[i]).Content;
            if (i != this.lstPickerType.SelectedItems.Count - 1) 
                r += ", ";
        }
        MessageBox.Show(r);
    }