1
votes

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

1
You have provided the code for the part that works, completely letting out the code for the part that has a problem. What you should have done, is included the textblock4 related code instead. Please do, and most likely you will be able to get more help. - Maxim V. Pavlov
i have provided the necessary code and it is giving runtime exception because listbox2 is completely empty and it needs to be filled at runtime - user1153545
how to dynamically load the runtime value " radian" into textblock4 on selecting "radian" from listbox2 ? - user1153545

1 Answers

1
votes

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);