Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WPF Datagrid: Get value from SelectionChanged event

Tags:

c#

wpf

datagrid

This has been driving me crazy all day. I just want the value of the selected row in a datagrid, it works in VB.net, I'm a little new to c# and I can't get it to work.

In VB my working code is:

Private Sub dg_qc_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)

        Dim TempListItem As QCProperties = CType(sender, DataGrid).SelectedItem

        Dim temp1 As String = TempListItem.PartNumber

End Sub

In C# I have:

    private void dg_blockList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        dgProperties tempItems = ((DataGrid)sender).SelectedItem;

        string tempModel = tempItems.modelRev;
        string tempDate = tempItems.date;
    }

I get the error "cannot implicitly convert type 'object' to "my properties class" (are you missing a cast?)

I have searched the internet and I have had no luck, I know its a simple fix. Please help.

Thanks, Chelsey

like image 850
Chelsey9 Avatar asked Sep 14 '25 14:09

Chelsey9


1 Answers

You just need to cast the SelectedItem to the right type:

dgProperties tempItem = ((DataGrid)sender).SelectedItem as dgProperties;

Note that you should check to make sure tempItems != null before accessing properties like modelRev and date.

like image 134
Colin Thomsen Avatar answered Sep 17 '25 03:09

Colin Thomsen