I am populating a ListView
from a Linq to SQL query list with this:
private void loademployeelist()
{
dbml.hrdbDataContext listpeople = new dbml.hrdbDataContext();
var q = from p in listpeople.EmpIDs
join pi in listpeople.EmpBasicFiles on p.EmpID1 equals pi.EBF_EmpID
where pi.EBF_Active == activeornot
orderby p.LastName
select new classes.Employeeselected() { FirstName = p.FirstName, LastName = p.LastName, empid=p.EmpID1};
foreach (var item in q)
{
lb_active_employee_names.Items.Add(new { LastName = item.LastName, FirstName = item.FirstName, empid = item.empid });
}
}
The problem is that I just want the selected value to be the empid
. I have looked everywhere and can't find a way to get that value. The code to get the value is this:
private void lb_active_employee_names_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListViewItem empsel = (ListViewItem)lb_active_employee_names.SelectedItem;
string test = empsel.GetType().ToString();
MessageBox.Show(test);
}
I keep getting an error when running the program after I select it. I tried looking up the error, but I am getting lost into this vast wilderness. I think I conceptually understand what is going on, but I don't know how to fix it. I am still very new to C#/Visual Studio.
Here is the error:
An exception of type 'System.InvalidCastException' occurred in 6DegreesGateway.exe but was not handled in user code
Additional information: Unable to cast object of type '<>f__AnonymousType103[System.String,System.String,System.Decimal]' to type 'System.Windows.Controls.ListViewItem'.
My XAML looks like this:
<ListView x:Name="lb_active_employee_names" HorizontalAlignment="Left" Height="135" Margin="10,148,0,0" VerticalAlignment="Top" Width="365" Grid.Column="1" Grid.Row="1" Loaded="listBox_Loaded" SelectionChanged="lb_active_employee_names_SelectionChanged" SelectedItem="{Binding Path=empid}">
<ListView.View>
<GridView>
<GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" />
<GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" />
<GridViewColumn Header="Employee ID" DisplayMemberBinding="{Binding empid}" />
</GridView>
</ListView.View>
</ListView>
I tried reviewing what others have done, Binding or creating a class etc. But I am just getting more and more confused.