Reputation: 359
I'm currently trying to get the contents of a selected row in a DataGrid
to appear in individual text boxes outside of the DataGrid
when a button is pressed. As it stands, I can get the values into their respective textboxes, however instead of just giving me the cell value as a string like I want it to, the textboxes display the value type like this: System.Windows.Controls.DataGridCell: Leary.
I've tried converting the cell value to a string a couple different ways, but my latest attempt to do this looks like this:
var rowSelection = EditGrid.GetSelectedRow(myGrid);
var columnSelection = EditGrid.GetCell(myGrid, rowSelection, 3);
string cellToEdit = Convert.ToString(columnSelection);
customerNameTxt.Text = cellToEdit;
I can supply the EditGrid class that I created if someone would like to see it, however, I do not think that's where the issue is since I am getting the correct cell into each textbox; I'm hoping it's simply a formatting issue.
Thanks in advance to anyone who can help
Upvotes: 1
Views: 2043
Reputation: 7058
How are you UI logic implemented? Things like this in WPF are really easy when you do it the MVVM way. If your DataGrid
works bound to a collection of entities, you can just bind your TextBox.Text
to a property of the DataGrid.SelectedItem
.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid x:Name="LayoutRoot">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<DataGrid x:Name="MyDataGrid" ItemsSource="{Binding Items}"/>
<TextBlock Grid.Column="1" Text="{Binding SelectedItem.MyProperty, ElementName=MyDataGrid}"/>
</Grid>
</Window>
Upvotes: 0
Reputation: 2151
Try to cast it to your UIElement
:
string cellToEdit = ((TextBlock)columnSelection.Content).Text;
Upvotes: 1