WPF binding data from datagrid to textbox

19,351

I'm always binding SelectedItem (datagrid Property) to a Property in my ViewModel. And then you can bind the Controls to this property. You also can achieve this without a viewmodel only with xaml:

<StackPanel>
    <TextBox Text="{Binding SelectedItem.Name, ElementName=myDataGrid}"/>
    <DataGrid x:Name="myDataGrid" />
</StackPanel>
Share:
19,351
Alfred Angkasa
Author by

Alfred Angkasa

like to try something new!

Updated on July 28, 2022

Comments

  • Alfred Angkasa
    Alfred Angkasa almost 2 years

    i'm new to WPF and still learn on it. I create a sample application and connect to the database. After i select data to the database, i can show it into my datagrid. Now, my concern is i want to bind to textbox depends on the row from my datagrid.

    so, whenever i click or select row in my datagrid, i bind the value to textbox. i already do some google and tried. but still failed. is there any solution? thanks.

    here is my application picture. enter image description here

    how is the xaml look like to bind for example row no 3 to my textbox? is there any class i should implement? because in windows form i just need to call cellclick. thanks.

  • Alfred Angkasa
    Alfred Angkasa over 11 years
    thanks for your answer. thats mean i have to implement a datagrid property in my code .cs, after that i alos change the .xaml? but do you have any sample code? thanks.
  • doerig
    doerig over 11 years
    You mentioned that you are new to WPF, so I highly recommend reading on MVVM Pattern (Model View ViewModel). I have added a code example to my answer that uses only xaml
  • Alfred Angkasa
    Alfred Angkasa over 11 years
    wait.. i got it.. thanks. How about if we change on the datagrid? i mean instead of bind, we also can change the value inside the datagrid.
  • doerig
    doerig over 11 years
    myDataGrid is the name of the datagrid. SelectedItem is a reference to the item that is currently selected in the grid. SelectedItem.Name is a arbitrary chosen Property. You can use any Property that is implemented in the class of the items that you have added to the grid
  • Alfred Angkasa
    Alfred Angkasa over 11 years
    now i understand. but how about by clicking the row in my datagrid, i also can edit/type, after that save to my database. is that possible?
  • doerig
    doerig over 11 years
    Sure you can, but there are many possibilities to do this. In my projects I am using an ORM (nHibernate) that handles the persistence of my objects. You could also use EntityFramework or directly Ado.net ...
  • Alfred Angkasa
    Alfred Angkasa over 11 years
    thanks for your time and answer.. i will search on what you suggest.. thanks. :)