Dynamic Form and Grid with C# in WPF

Ever wanted to generate the form & grid dynamically and add data from some data source? Here's to help you.

Create a WPF project in Visual Studio. Add a UserControl and name it mainUserControl.xaml
Now add a stackpanel just like this :
<UserControl x:Class="TestApp.mainUserControl"
             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" 
             xmlns:local="clr-namespace:SaiData.TestApp"
             mc:Ignorable="d" 
             >
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="5*"/>
            <ColumnDefinition Width="43*"/>
        </Grid.ColumnDefinitions>
        <StackPanel Name="panel1" Margin="18.971,24,24,0" Grid.Column="1">

        </StackPanel>
    </Grid>
</UserControl>
Now, go to mainUserControl.cs file :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestApp
{
    /// <summary>
    /// Interaction logic for mainUserControl.xaml
    /// </summary>
    public partial class mainUserControl : UserControl
    {
      public mainUserControl(){
        InitializeComponent();
        
        TextBlock tb = new TextBlock();
        tb.Text = "Username :";
        tb.Width = 100;
        tb.HorizontalAlignment = HorizontalAlignment.Left;
        panel1.Children.Add(tb);
        TextBox username = new TextBox();
        username.Width = 100;
        username.HorizontalAlignment = HorizontalAlignment.Left;
        panel1.Children.Add(username);

        TextBlock tb1 = new TextBlock();
        tb1.Text = "Full Name :";
        tb1.Width = 100;
        tb1.HorizontalAlignment = HorizontalAlignment.Left;
        panel1.Children.Add(tb1);
        TextBox fullname = new TextBox();
        fullname.Width = 100;
        fullname.HorizontalAlignment = HorizontalAlignment.Left;
        panel1.Children.Add(fullname);
        
        ComboBox cb = new ComboBox();
        cb.Width = 150;
        cb.HorizontalAlignment = HorizontalAlignment.Left;
        cb.Margin = new Thickness(0, 5, 0, 0);
        CustomerData[] customer_list = gd.getCustomerRecord();
        cb.Items.Add("Select Gender");
        cb.Items.Add("Male");
        cb.Items.Add("Female");
        cb.Items.Add("Other");
        cb.SelectedIndex = 0;
        panel1.Children.Add(cb);
        
        TextBlock tb2 = new TextBlock();
        tb2.Text = "Full Name :";
        tb2.Width = 100;
        tb2.HorizontalAlignment = HorizontalAlignment.Left;
        panel1.Children.Add(tb2);
        TextBox password = new TextBox();
        password.Width = 100;
        password.HorizontalAlignment = HorizontalAlignment.Left;
        panel1.Children.Add(password);
        
        Button submit = new Button();
        submit.Name = "submit_user";
        submit.Width = 100;
        submit.HorizontalAlignment = HorizontalAlignment.Left;
        submit.Content = "Save user Data";
        submit.Margin = new Thickness(0, 5, 0, 0);
        submit.Click += (s, e) =>
        {
            //here you can define action for submitting form.
            MessageBox.Show("username = " + username.Text);
        };
        panel1.Children.Add(submit);
      }
    }
}
This will create a form dynamically on your UserControl. Now to add dynamic grid with Edit/Delete buttons add this code to your existing UserControl or make a new UserControl :
DataGrid dg = new DataGrid();
dg.HorizontalAlignment = HorizontalAlignment.Left;     
dg.VerticalAlignment = VerticalAlignment.Top;
dg.AutoGenerateColumns = true;            
//the function getData used to get the data from data-source, you can manipulate it. 
getData gd = new getData(); // getData holds getUserRecord() to get the data 
UserData[] data = gd.getUserRecord();       
dg.ItemsSource = data;
FrameworkElementFactory sp = new FrameworkElementFactory(typeof(StackPanel)); 
sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);     
FrameworkElementFactory delete = new FrameworkElementFactory(typeof(Button)); 
delete.AddHandler(Button.ClickEvent, new RoutedEventHandler((s, e) => { 
MessageBox.Show(data[dg.SelectedIndex].id); })); 
delete.SetValue(ContentControl.ContentProperty, "Delete");
FrameworkElementFactory edit = new
FrameworkElementFactory(typeof(System.Windows.Controls.Button)); 
edit.AddHandler(Button.ClickEvent, new RoutedEventHandler((s, e) => {
MessageBox.Show("edited click!"); }));
edit.SetValue(ContentControl.ContentProperty, "Edit");
edit.SetValue(FrameworkElement.MarginProperty, new Thickness(5, 0, 0, 0));
sp.AppendChild(delete);        
sp.AppendChild(edit);
DataGridTemplateColumn dataGridTemplateColumn = new DataGridTemplateColumn()
{                
Header = "new...",    
CellTemplate = new DataTemplate { VisualTree = sp }     
};
dg.Columns.Add(dataGridTemplateColumn);  
panel1.Children.Add(dg);
That's it. You Just made a dynamically generated grid and form.

PS: The new code panel is added using the http://blogger-editor.xyz

Comments