简体   繁体   中英

C# WPF Datagrid: Get value from SelectionChanged event

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM