Search code examples
c#mysqlwpfdatagrid

DataGridView C# wpf select row to textboxes


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.


Solution

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