0

i am trying to get SelectedValue for selected item in listbox and then perform action to get id from database. Below is the code I am trying on Context Menu long press

var selected = (NewsData)lstNews.SelectedValue;
int a = selected.newsID;
MessageBox.Show(a.ToString());

but than it throws error.

Additional information: Object reference not set to an instance of an object. this is because we can get selectedvalue only on select tap event but how to achieve same on long press context menu click event .

bit
  • 4,407
  • 1
  • 28
  • 50
SD7
  • 514
  • 8
  • 25
  • [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Oct 01 '14 at 06:51
  • i know it is null but if i use same code on select tap event it works fine .i want it to work on longpress contextmenu click @SonerGönül – SD7 Oct 01 '14 at 06:55
  • I suspect context menu click action doesn't set `SelectedValue` by default, you can use `sender` parameter instead. Post relevant XAML markup, particularly the listbox. – har07 Oct 01 '14 at 07:29
  • how to do that?? @har07 – SD7 Oct 01 '14 at 07:41

1 Answers1

2

I suspect that's because context menu click action doesn't set SelectedValue by default. You can get information that correspond to clicked item from sender parameter instead, for example (assuming that the ListBox markup looks like the one posted in the previous question) :

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    var menuItem = (MenuItem)sender;
    var ctxMenu = (ContextMenu)menuItem.Parent;
    var stackpanel = (StackPanel)ctxMenu.Owner;
    var selected = (NewsData)stackpanel.DataContext;
    int a = selected.newsID;
    MessageBox.Show(a.ToString());
}
Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137