Getting selected Item in DataGrid in WPF

前端 未结 2 1423
再見小時候
再見小時候 2021-01-27 02:30

I have a datagrid and textboxes. When I select a row in DataGrid I want the textboxes to be filled with related data of that datagrid column. Here is the picture.,

相关标签:
2条回答
  • 2021-01-27 03:12

    Here's how you could do it with bindings. The "Text" parameter of each textbox should be modified thusly:

    Text = "{Binding ElementName = personelEntityDataGrid, Path = CurrentItem.<FIELD_NAME_HERE>}"
    

    so for the nameBox, you would have:

    Text = "{Binding ElementName = personelEntityDataGrid, Path = CurrentItem.Name}"
    
    0 讨论(0)
  • 2021-01-27 03:15

    Don't check in Loaded event, instead Check in selectionChanged event, also add a null check to your pers object

    private void personelEntityDataGrid_SelectionChanged(object sender, RoutedEventArgs e)
    {
        PersonelEntity pers = (PersonelEntity)personelEntityDataGrid.SelectedItem;
        if(pers != null)
        {
        NameBox.Text = pers.Name; // I get exception here
        AgeBox.Text = pers.Age.ToString();
        PhoneNumberBox.Text = pers.PhoneNumber;
        AddresBox.Text = pers.Address;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题