Search code examples
wpfwpf-controlswpfdatagrid

How to create usercontrol using Gridview and Textbox in wpf


I wanted to create a usercontrol in WPF using a gridview and a textbox.

I wanted to show data on the textbox when a row is selected in the gridview.


Solution

  • Please Find Solution as below :

    UserControl XAML Code

    <UserControl x:Class="WpfApplication1.DataGridControl"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" 
                 d:DesignHeight="300" d:DesignWidth="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="15*"></RowDefinition>
                <RowDefinition Height="85*"></RowDefinition>
    
            </Grid.RowDefinitions>  
            <TextBox x:Name="txtvalue" Width="100" Grid.Row="0" />
            <DataGrid x:Name="dg" SelectionChanged="dg_SelectionChanged" ItemsSource="{Binding Path=.}" Grid.Row="1" IsReadOnly="True" />
        </Grid>
    </UserControl>
    

    Usercontrol Code behind

    using System;
    using System.Data;
    using System.Windows.Controls;
    
    namespace WpfApplication1
    {
        /// <summary>
        /// Interaction logic for DataGridControl.xaml
        /// </summary>
        public partial class DataGridControl : UserControl
        {
            public DataGridControl()
            {
                InitializeComponent();
                DataTable dt = new DataTable();
                dt.Columns.Add("Column1");
                dt.Columns.Add("Column2");
    
                dt.Rows.Add("Ashok", "Rathod");
                dt.Rows.Add("Paresh", "Jadav");
                dt.Rows.Add("Keyur", "Kamdar");
    
                dt.AcceptChanges();
    
                dg.DataContext = dt;
            }
    
            private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                DataRowView obj = dg.SelectedItem as DataRowView;
                if(obj != null)
                { 
                    txtvalue.Text=Convert.ToString(obj.Row["Column1"]);
                }
            }
        }
    }
    

    MainWindow Xaml for use of usercontrol

    <Window x:Class="WpfApplication1.UserControlMainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:uc="clr-namespace:WpfApplication1"
            Title="UserControlMainWindow" Height="300" Width="300">
        <Grid>
            <uc:DataGridControl />
        </Grid>
    </Window>