WPF binding data from datagrid to textbox
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>
Comments
-
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.
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 over 11 yearsthanks 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 over 11 yearsYou 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 over 11 yearswait.. 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 over 11 yearsmyDataGrid 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 over 11 yearsnow 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 over 11 yearsSure 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 over 11 yearsthanks for your time and answer.. i will search on what you suggest.. thanks. :)