Question

Can some1 please give me an example or a code, how to display data from datagrid to textbox in c# - wpf app.

I've tried to do it like in Windows Forms application, but the code doesn't work.

if (e.RowIndex >= 0)
        {
            DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];

            name.Text = row.Cells["Name"].Value.ToString();
            lastName.Text = row.Cells["LastName"].Value.ToString();
            userName.Text = row.Cells["UserName"].Value.ToString();
            password.Text = row.Cells["Password"].Value.ToString();
        }
Was it helpful?

Solution

First, WPF is not WinForms, trying to code thing the same way is just going to cause you pain. What you are trying to do is actually really easy in WPF! The shortest solution is to bind directly to the DataGrid SelectedItem property:

<DataGrid x:Name="UserGrid" ItemsSource="{Binding Users}">
...
</DataGrid>

<TextBox Text="{Binding ElementName=UserGrid, Path=SelectedItem.Name}"/>
...More of the same...

Now this assumes that the DataGrid is bound to a collection of the "User" class (which it absolutely should be) in your ViewModel (NOT your code-behind). The other way would be to bind SelectedItem and then have the other controls bind to that, like so:

<DataGrid x:Name="UserGrid" ItemsSource="{Binding Users}" SelectedItem="{Binding CurrentUser}">
...
</DataGrid>

<TextBox Text="{Binding Path=CurrentUser.Name}"/>
...More of the same...

Of course you now need a "CurrentUser" property in your ViewModel to bind to. Both ways are equally valid approaches, just decide which you like better. The second is better if you need the "CurrentUser" object for something else in code, the first is a bit quicker and doesn't have the shell property if you don't need it. In case you haven't done anything with MVVM, here is a great tutorial (MSDN).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top