0

I have a form with a data grid view and text boxes in C# WPF. I get data from MySql Database using the search option based on name and Lastname on my fields.

                MySqlCommand cmd = new MySqlCommand("SELECT * FROM  owners WHERE name='" + namesearch + "' OR last_name= '" + lastnamesearch + "'", conn);

and I bind some of the basic data like Name, Lastname, phone, national id into my Datagrid.

            <DataGrid.Columns>
            <DataGridTextColumn  Header="" Width="3" IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding Path=name}" Header="نام" Width="150" IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding Path=last_name}" Header="نام خانوادگی" Width="150" IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding Path=national_code}" Header="کد ملی" Width="200" IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding Path=father_name}" Header="نام پدر" Width="100" IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding Path=mobile}" Header="شماره همراه" Width="150" IsReadOnly="True" />
        </DataGrid.Columns>

now I want to have this option: when I chose a row from data grid view rows, all the data I get with my query command before, just appear in text boxes, for example, the name goes to TexboxName last name goes to TexboxLastname, and also all other data I get but did not show in Datagrid view. these are the fields I have on my table

enter image description here

I have a text box for each one of them sorry for my bad English I hope you understand.

Arsalan Ahmadi
  • 55
  • 1
  • 10

1 Answers1

1

You could bind the TextBox to the SelectedItem property of the DataGrid:

<DataGrid x:Name="dg" ... />

<TextBox x:Name="TexboxName" Text="{Binding SelectedItem.name, ElementName=dg}" />
mm8
  • 163,881
  • 10
  • 57
  • 88
  • The problem is i did not bind all the datas into the DataGrid. only name and last name are bind into DataGrid l, for example there is a search box for name when someone search John, all the results of Johns (name, lastname and id) will appear into DataGrid and if i chose one of them the rest of the feilds (phone, address, birthday and...) Appear into text boxes. – Arsalan Ahmadi Nov 04 '21 at 20:29
  • Tha's why you should bind to the `SelectedItem` property of the `DataGrid` (see my edit). It returns the object that has all those properties/columns even if you only see a subset of them in the `DataGrid`. – mm8 Nov 04 '21 at 20:33
  • I got it man, it worked, thanks for help, you make my day <3 – Arsalan Ahmadi Nov 05 '21 at 07:06