AlexisRS
AlexisRS

Reputation: 19

WPF DataGrid in textbox

I have a WPF DataGrid in XAML and C # and I want to select a row and display the row in the text box, it is not a DataGridView

x:Name="dtGConsultas" ItemsSource= "{Binding }" 
HorizontalAlignment="Left" Margin="12,3,0,0" Grid.Row="6" VerticalAlignment="Top" 
Grid.ColumnSpan="5" Height="111" Width="598" Grid.RowSpan="3" 
SelectionChanged="dtGConsultas_SelectionChanged"/>

Upvotes: 1

Views: 2621

Answers (2)

Tatranskymedved
Tatranskymedved

Reputation: 4371

This can be done in several ways:

  1. You can bind SelectedItem to some property and then display it
  2. You can bind TextBox value to the DataGrid's SelectedItem
  3. You can set the TextBox value on each call of SelectionChanged method

If You would be using MVVM pattern, You should pick 1st option.

Other 2nd an 3rd options are useful for You, but in bigger (complex) applications this solutions would cause issues to read the code easily & maintain it. Not recommended.


Examples:

  1. MVVM approach

ViewModel file:

using using System.Collections.ObjectModel;

public class MyViewModel
{
    //add implementation of INotifyPropertyChange & propfull
    public ObservableCollection<MyItem> MySrcList { get; set; }

    //add implementation of INotifyPropertyChange & propfull
    public MyItem SelectedItem { get; set; }
}

View:

<UserControl ...
    xmlns:local="clr-namespace:MyProject">
    <UserControl.DataContext>
        <local:MyProject />
    </UserControl.DataContext>

    ...

    <DataGrid
         ItemsSource="{Binding MySrcList}"
         SelectedItem="{Binding SelectedItem}"/>

  1. Binding TB value to value of DataGrid's SelectedItem

Xaml file:

<Grid>
    <DataGrid
        x:Name="dtGConsultas"
        ItemsSource="{Binding MySrcList}"/>
    <TextBox Text="{Binding dtGConsultas.SelectedItem, Mode=OneWay}"/>
</Grid>

Code-behind (C# file):

public class MyUserControl
{
    public MyUserControl()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }

    public List<MyItem> MySrcList = new List<MyItem>();
}

  1. Update in method (Code-behind):

Xaml file:

<Grid>
    <DataGrid
        x:Name="dtGConsultas"
        ItemsSource="{Binding MySrcList}" 
        SelectionChanged="dtGConsultas_SelectionChanged"/>
    <TextBox x:Name="MyTbx"/>
</Grid>

Code-Behind (C# file):

public class MyUserControl
{
    public MyUserControl()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }

    public List<MyItem> MySrcList = new List<MyItem>();

    private void dtGConsultas_SelectionChanged( /* args */)
    {
        MyTbx.Text = dtGConsultas.SelectedItem.ToString();
    }
}

Upvotes: 2

Nadjib FODIL CHERIF
Nadjib FODIL CHERIF

Reputation: 1

You can also add a column that contains a checkbox and you bind it. Then juste check if (Your_List.element.CheckBox==true). you can get a list whit your checked elements

Upvotes: 0

Related Questions