title: Get the values of a SelectedItem in wpf
body: <p>I have a ListBox in a WPF Page each Item of which consists of two Labels. I have assigned them the names FirstName, LastName:</p>
  
  <pre><code>&lt;ListBox.ItemTemplate&gt;
              &lt;DataTemplate&gt;
                  &lt;Grid&gt;
                      &lt;Grid.ColumnDefinitions&gt;
                          &lt;ColumnDefinition Width="Auto"/&gt;
                          &lt;ColumnDefinition Width="Auto"/&gt;
                      &lt;/Grid.ColumnDefinitions&gt;
                      &lt;TextBlock Grid.Column="0" Name="FirstName" Text="{Binding FirstName}" Margin="0,0,10,0"/&gt;
                  &lt;TextBlock Grid.Column="1" Name="LastName" Text="{Binding LastName}" HorizontalAlignment="Left"/&gt;
                  &lt;/Grid&gt;
              &lt;/DataTemplate&gt;
          &lt;/ListBox.ItemTemplate&gt;
  </code></pre>
  
  <p>When the user selects an Item of the Listbox, I want to hold their values separately in order to pass them to another Page. I try to this end in the code behind the code: </p>
  
  <pre><code> ListItemCollection lbi = List1.SelectedItem as ListItemCollection;
  
          string first = lbi.FirstListItem.DataContext.ToString();
          string last = lbi.LastListItem.DataContext.ToString();
  </code></pre>
  
  <p>However I get a nullReferenceException at the definition of strings? What is wrong in this way? How can I get the SelectedItem values?   </p>
  
  <p><strong>Update:</strong> The Binding values derive from an SQLAdapter with a SQL Query. See the code behind:</p>
  
  <pre><code>SqlDataAdapter dAdapt1 = new SqlDataAdapter(sqlStr1, cnStr);
  
          DataSet dataSet1 = new DataSet();
          dAdapt1.Fill(dataSet1);
  
          List1.DataContext = dataSet1.Tables[0];
  </code></pre>