Skip to main content

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

Popular posts from this blog

Live Game Streaming on YouTube

Hello Guys, Today I gonna talk about how to stream your mobile gameplay to YouTube Gaming. Nowadays, PUBG (PlayerUnknown's BattleGround) is the most trending mobile game. Many Pro players upload/stream their gameplay to YouTube and earn money through monetization. Ok. Let's start. First of all Download YouTube Gaming App. After download, open the app and create/choose your google account for your YouTube channel. If you're a new user then you have to wait for 24 hours until you stream your gameplay (YouTube need to activate your account). Now Just click on the first icon(streaming icon) on the top left corner and this screen will appear: Click Next and select Stream if you want to live stream your gameplay or Record if you want to save the video to your phone and upload it later. Select the video format you want to upload/stream. Click next, you'll see a tips screen, read it and click next. Now, Select the game you want to stream or record. Add the st

Give Her Wings - Women's day special

Woman equality . A burning issue in the current world. How we can manage to get through this? an obvious answer is " Equal parenting to boy and girl." This is the base to start achieving the goal. Why differentiate the parenting to boy and girl? Giving boys all the freedom and for a girl its ban to go out alone! Isn’t there something wrong? Why should boys have all the fun? If you have a baby girl, it’s a blessing, cheer her, encourage her and protect her. Yes, it’s hard to be a parent of a girl child in this cruel minded culture where we read the news of acid attacks and rap every second day. Yes, it is the duty of every parent to make their children safe, But don’t be so overprotective that she feels the burden over her head. As Newton's third law, as hard as you push the spring, it’ll bounce back to you with the same force.  Give her freedom to be herself. If you gave her good sacrament than belief in her, she’ll not do anything wrong that ruin

Automate Build & Deploy React production build with gitlab-ci to Linux base server (AWS)

Right now as everyone wanting to automate literaly everything, this post will show you how you can automate the react build and deployment. I am using create-react-app getting started with react and assuming you have a similar setup. Setup .gitlab-yml file for gitlab auto deploy Here's the whole .gitlab-yml file that you can copy directly to root of your project. Breaking each line: image: node : 10 cache:   paths: - node_modules / This line define the node version that should be used by the docker instance of shared gitlab-runner and the path defines to cache the node_modules dir. before_script: - apt - get update - qq & & apt install - y openssh - client openssh - server - mkdir - p ~ / . ssh - echo - e " $SSH_PRIVATE_KEY " > ~ / deploy . pem - chmod 400 ~ / deploy . pem - '[[ -f /.dockerenv