user1153545
user1153545

Reputation: 13

windows phone listbox

1) This is my code for listbox2 selectionchanged

void PrintText2(object sender, SelectionChangedEventArgs args)
{
   if (null != listBox2.SelectedItem)
   {
      ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
      textBlock4.Text = lbi.Content.ToString();
   }
}

2) This my code for listbox1 selecionchanged

void PrintText1(object sender, SelectionChangedEventArgs args)
{  
   if (null != listBox1.SelectedItem)
   {
      ListBoxItem l = ((sender as ListBox).SelectedItem as ListBoxItem);
      textBlock6.Text = l.Content.ToString();
      if (textBlock6.Text == "Angle")
      { 
         loadlistAngle(); 
      }
   }
}

3)

void  loadlistAngle()
{            
   listBox2.Items.Clear(); 
   listBox2.Items.Add("Radian");
   listBox2.Items.Add("Degree");
}

4) listbox1 contains static item "Angle" and on selection of "Angle" at runtime,Angle gets loaded in textBolck6 and then new items "radian" and " degree" gets added to listbox2

5) after this when I click "radian" of listbox2 ,the "radian value doesn't get loaded into textblock4 ,it gives "NullReferenceException" in "lbi.Content.ToString()"

6) how do I modify my code so that at runtime "radian" value get loaded in textblock4 and new items generated will get selected in listbox2

Upvotes: 1

Views: 598

Answers (1)

Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

Run your code in the debugger after adjusting it the following way:

Where you have textBlock4.Text = lbi.Content.ToString(); replace it with:

object lbiContent  = lbi.Content;

if(lbiContent != null) textBlock4.Text = lbiContent.ToString();

Put a break point at the object line. This way you will know what exactly is the contents of your listboxitem, and if it is null.

Most likely you are just placing something wrong in

listBox2.Items.Clear(); 
listBox2.Items.Add("Radian");
listBox2.Items.Add("Degree");

Other then that, everything is correct in the code you have provided.

Update:

Also, try substituting

ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);

with

ListBoxItem lbi = ((sender as ListBox).SelectedItem;

You don't need to do a double cast.

And the Selected item of the list box may still be empty.

Update 2:

Most likely this shoud be how you retrieve the selected item:

ListBoxItem lbi = (args.AddedItems[0] as ListBoxItem);

Upvotes: 1

Related Questions