emre kaplan
emre kaplan

Reputation: 198

c# wpf datagridview selected row

I got a datagridview with a information of customers. I have background data which I don't represent on datagridview. I try to get customer id on a selected row in datagrid. I try to use this code, but I got an error at converting datagrid.SelectedItem to DataViewRow.

Here is my C# code;

private void searchPayment_btn_Click(object sender, RoutedEventArgs e)
    {
        DataRowView drv = (DataRowView)customerDataGrid.SelectedItem;
        String result = (drv["customer_id"]).ToString();
        presenter.getSelecetedCustomerPayment(Convert.ToInt32(result));
    }

In debug mode, I can see customerDataGrid.SelectedItem is correct. It returns all my data including "customer_id".

and this is the XAML code for my datagrid;

<DataGrid x:Name="customerDataGrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="10,10,326,10" AutoGenerateColumns="False" IsReadOnly="True">
                    <DataGrid.Columns>
                        <DataGridTextColumn Binding="{Binding tc_id_no}" Header="National ID"/>
                        <DataGridTextColumn Binding="{Binding firstname}" Header="Name"/>
                        <DataGridTextColumn Binding="{Binding lastname}" Header="Lastname"/>
                        <DataGridTextColumn Binding="{Binding group_name}" Header="Group"/>
                        <DataGridTextColumn Binding="{Binding birthdate}" Header="Birthdate"/>
                        <DataGridTextColumn Binding="{Binding parent_name}" Header="Parent Name"/>
                        <DataGridTextColumn Binding="{Binding phone_number}" Header="Phone"/>
                        <DataGridTextColumn Binding="{Binding email}" Header="Email"/>
                        <DataGridTextColumn Binding="{Binding gender}" Header="Gender"/>
                    </DataGrid.Columns>
                </DataGrid>

Upvotes: 0

Views: 2739

Answers (2)

Ahmed Alblooshi
Ahmed Alblooshi

Reputation: 19

try this : DataRowView row = (DataRowView)DataGrid.SelectedItems[0];

0 is the first item in the first intersection, try getting the index by trial and error method, keep playing with the index until you get the index you want.

Upvotes: 0

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

The SelectedItemProperty returns the (first) currently selected item of your DataGrid. This means this is an object of your Customer class (thats the name of the class I suppose) and no DataRowView or something like that. You can simply get any properties of your Customer if you cast the selected item. Note that you have to check if the selected item is null since no selected item is possible:

Customer selectedCustomer = customerDataGrid.SelectedItem as Customer;
if (selectedCustomer != null)
{
    //Get the properties you need
    string selectedCustomerId = selectedCustomer.Id;
}

Upvotes: 1

Related Questions