M_K
M_K

Reputation: 3455

Getting selected value from ListBoxItem, returns null

I'm having a problem with a LisBox that I am filling, when I tap on a item it gives me the error

"Value does not fall within the expected range."

and when I put a break point on the line that gets the selected value it says its value is null, I had the list items declared statically previously in xaml and it worked no problem.

Can any help me?

private void listbox_tapped(object sender, TappedRoutedEventArgs e)
    {
        ListBoxItem selected = (lbLetter.SelectedValue as ListBoxItem);

        int listitem = lbLetter.SelectedIndex;

        if (lbLetter.Items.Count != 0)
        {

            lbWord.Items.Add(selected);
        }

    }

   private void RandomizeListbox()
    {
        List<char> values = new List<char>();


        for (int i = 0; i<=MAXLETTERS; i++)
        {
            values.Add(RandomLetter());
        }
        lbLetter.ItemsSource = values;
    }

    public static char RandomLetter()
    {
        return alphabet[random.Next(alphabet.Length)];
    }

Upvotes: 0

Views: 384

Answers (2)

Rob Maas
Rob Maas

Reputation: 475

Without testing it, I can assure you that the following line is incorrect:

ListBoxItem selected = (lbLetter.SelectedValue as ListBoxItem);

The SelectedValue property does not return a ListBoxItem object, it returns a string. See http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.primitives.selector.selectedvalue.aspx for more information.

Upvotes: 0

Alex
Alex

Reputation: 841

May be this happens because there several the same values in a char array. Try this:

for (int i = 0; i <= MAXLETTERS; i++)
{
    var c = RandomLetter();
    if(!values.Contains(c))
        values.Add(c);
}

Upvotes: 1

Related Questions