Sabyasachi Mishra
Sabyasachi Mishra

Reputation: 1747

Get DataGrid Selected Row value bind through list in WPF

I have a DataGrid which I am binding through list as follows

<DataGrid Name="GridCoutry" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding Id}" Width="*"/>
        <DataGridTextColumn Header="Country Name" Binding="{Binding CountryName}" Width="*"/>
        <DataGridTextColumn Header="Country Code" Binding="{Binding CountryCode}" Width="*"/>
        <DataGridTemplateColumn Header="Actions" Width="*">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Button Content="Delete" Name="BtnDelete" Click="BtnDelete_Click" MinWidth="100" Margin="0,0,10,0"/>
                        <Button Content="Edit" x:Name="BtnEdit" Click="BtnEdit_Click" MinWidth="100" Margin="0,0,10,0"/>
                    </StackPanel>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

I am binding DataGrid as follows

public static List<Country> GetCountryList()
{
    List<Country> CountryData = new List<Country>();
    using (var sr = new StreamReader(@"CountryCodes"))
    {
        string line;
        int i = 0;
        while ((line = sr.ReadLine()) != null)
        {
            i++;
            Country C_Data = new Country();
            int index = line.LastIndexOf(" ");
            C_Data.Id = i;
            C_Data.CountryName = line.Substring(0, index);
            C_Data.CountryCode = line.Substring(index + 1);
            CountryData.Add(C_Data);
        }
    }
    return CountryData;
}

and on window load

GridCoutry.ItemsSource = GetCountryList();

enter image description here

I wrote the following code to get the CountryName of Selected Edit button

private void BtnEdit_Click(object sender, RoutedEventArgs e)
{
    var drv = GridCoutry.SelectedItem as DataRowView;
    if (drv == null) return;
    var CountryName = drv[1].ToString();
}

My drv return's null but when I see at GridCoutry.SelectedItem I get the selected value which I wanted.

Don't know where I am going wrong?

Upvotes: 0

Views: 853

Answers (1)

Navoneel Talukdar
Navoneel Talukdar

Reputation: 4608

You should cast your selected item to correct type.

Country selectedCountry = (Country)GridCoutry.SelectedItem;

Otherwise another option to bind SelectedItem with your class/viewmodel

<Grid DataContext="<ViewModel Name>">
    <DataGrid ItemsSource="{Binding Path=Country}"
              SelectedItem="{Binding Path=SelectedCountry, Mode=TwoWay}"/>
</Grid> 

Upvotes: 1

Related Questions