Getting selected Item in DataGrid in WPF

与世无争的帅哥 提交于 2021-02-05 08:33:26

问题


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.,

enter image description here

I have written this code in MainWindow.xaml.cs :

private void personelEntityDataGrid_Loaded(object sender, RoutedEventArgs e)
{
    PersonelEntity pers = (PersonelEntity)personelEntityDataGrid.SelectedItem;

    NameBox.Text = pers.Name; // I get exception here
    AgeBox.Text = pers.Age.ToString();
    PhoneNumberBox.Text = pers.PhoneNumber;
    AddresBox.Text = pers.Address;


}

When I run the code I get the null reference exception in the line that I wrote. Here is the exception:

{"Object reference not set to an instance of an object."}

I guess the object pers is null. Can you tell me how to make this work?

Here is my xaml file :

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Personel" mc:Ignorable="d" x:Class="Personel.MainWindow"
        Title="MainWindow" Height="500" Width="725" Loaded="Window_Loaded">
    <Window.Resources>
        <CollectionViewSource x:Key="personelEntityViewSource" d:DesignSource="{d:DesignInstance {x:Type local:PersonelEntity}, CreateList=True}"/>
    </Window.Resources>
    <Grid DataContext="{StaticResource personelEntityViewSource}" >
        <Label Content="Personnel
               " HorizontalAlignment="Left" Margin="55,47,0,0" VerticalAlignment="Top"/>
        <Button Content="Delete" HorizontalAlignment="Left" Margin="344,47,0,0" VerticalAlignment="Top" Width="75" Click="Delete_Button_Click"/>
        <Button Content="Add" HorizontalAlignment="Left" Margin="477,47,0,0" VerticalAlignment="Top" Width="75" Click="Add_Button_Click"/>
        <Button Content="Update" HorizontalAlignment="Left" Margin="624,47,0,0" VerticalAlignment="Top" Width="75" Click="Update_Button_Click"/>
        <Label Content="Name" HorizontalAlignment="Left" Margin="55,91,0,0" VerticalAlignment="Top"/>
        <Label Content="Age" HorizontalAlignment="Left" Margin="55,132,0,0" VerticalAlignment="Top"/>
        <Label Content="Phone Number" HorizontalAlignment="Left" Margin="55,178,0,0" VerticalAlignment="Top"/>
        <Label Content="Address" HorizontalAlignment="Left" Margin="55,218,0,0" VerticalAlignment="Top"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="309,95,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="367" Name="NameBox"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="309,136,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="57" Name="AgeBox"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="309,178,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120" Name="PhoneNumberBox"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="309,222,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="367" Name="AddresBox"/>
        <DataGrid x:Name="personelEntityDataGrid" AutoGenerateColumns="False" SelectionChanged="personelEntityDataGrid_SelectionChanged"  EnableRowVirtualization="True" ItemsSource="{Binding Path=.}" Margin="10,291,0,-22" RowDetailsVisibilityMode="VisibleWhenSelected" Loaded="personelEntityDataGrid_Loaded">
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="addressColumn" Binding="{Binding Address}" Header="Address" Width="SizeToHeader"/>
                <DataGridTextColumn x:Name="ageColumn" Binding="{Binding Age}" Header="Age" Width="SizeToHeader"/>
                <DataGridTextColumn x:Name="idColumn" Binding="{Binding Id}" Header="Id" Width="SizeToHeader"/>
                <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Name}" Header="Name" Width="SizeToHeader"/>
                <DataGridTextColumn x:Name="phoneNumberColumn" Binding="{Binding PhoneNumber}" Header="Phone Number" Width="SizeToHeader"/>
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

回答1:


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;
    }

}



回答2:


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}"


来源:https://stackoverflow.com/questions/24450729/getting-selected-item-in-datagrid-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!