0

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();
        }
1
  • @HamletHakobyan nothing because i do not know how to:s Commented Mar 25, 2014 at 21:23

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

3 Comments

one more question? I have like 10 textboxes and only 7 display data...i must have done something wrong. Which data exacly is Path=SelectedItem.Name...where can i find the "name" name?
Ok, great! Let me know if you run into anything else. A quick answer for anyone else that runs across this, "SelectedItem.Name" says look at the "SelectedItem" object of the element named in "ElementName", then get its "Name" property.
exactly. thank you very much and thanks for your time! appreaciate it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.