WPF - Add Treeview Items Depending On The Field From Database At Runtime

This article is related to my previous article which you can see by "Click Here".

In this article we will see how you can use the TreeView & how to add new items at runtime into TreeView from the
database. Here I have taken three radio buttons & they are in a group which means you can select only one radio button
at a time and the three buttons are used for adding values into the TreeView. Depending on the selected radio button it
will add that value into the TreeView at runtime from the database.

MainWindow.xaml Code : 

<Window x:Class="WPFAllDatabaseOperationApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="487" Width="700" Loaded="Window_Loaded">
    <Grid>
        <Label Content="Student ID" Height="28" HorizontalAlignment="Left" Margin="39,267,0,0" Name="label1" VerticalAlignment="Top" Width="77" Visibility="Visible" />
        <Label Content="Student Name" Height="28" HorizontalAlignment="Left" Margin="190,267,0,0" Name="label2" VerticalAlignment="Top" Width="94" Visibility="Visible" />
        <Label Content="Student Result" Height="28" HorizontalAlignment="Left" Margin="421,267,0,0" Name="label3" VerticalAlignment="Top" Width="94" Visibility="Visible" />
        <Button Content="Insert" Height="23" HorizontalAlignment="Left" Margin="90,301,0,0" Name="btnInsert" VerticalAlignment="Top" Width="75" Click="btnInsert_Click" />
        <DataGrid AutoGenerateColumns="True" Height="249" HorizontalAlignment="Left" Margin="225,12,0,0" Name="myDataGrid" VerticalAlignment="Top" Width="431" />
        <Button Content="Update" Height="23" HorizontalAlignment="Left" Margin="209,301,0,0" Name="btnUpdate" VerticalAlignment="Top" Width="75" Click="btnUpdate_Click" />
        <Button Content="Delete" Height="23" HorizontalAlignment="Right" Margin="0,301,268,0" Name="btnDelete" VerticalAlignment="Top" Width="75" Click="btnDelete_Click" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="521,269,0,0" Name="txtStudResult" VerticalAlignment="Top" Width="120" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="290,269,0,0" Name="txtStudName" VerticalAlignment="Top" Width="120" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="122,269,0,0" Name="txtStudId" VerticalAlignment="Top" Width="55" TextChanged="txtStudId_TextChanged" />
        <TreeView Height="249" HorizontalAlignment="Left" Margin="12,12,0,0" Name="MyTreeView" VerticalAlignment="Top" Width="199" />
        <RadioButton Content="Student Id" Height="16" HorizontalAlignment="Left" Margin="90,330,0,0" Name="RBStudId" VerticalAlignment="Top" GroupName="Student" Checked="RBStudId_Checked" />
        <RadioButton Content="Studnet Name" Height="16" HorizontalAlignment="Left" Margin="209,330,0,0" Name="RBStudName" VerticalAlignment="Top" GroupName="Student" IsChecked="True"  Checked="RBStudName_Checked" />
        <RadioButton Content="Student Result" Height="16" HorizontalAlignment="Right" Margin="0,330,244,0" Name="RBStudResult" VerticalAlignment="Top" GroupName="Student" Checked="RBStudResult_Checked" />
    </Grid>
</
Window>

In the above code for the RadioButton you must set the GroupName so It will allow select only one radio button at a one time and for that you must provide the same name for all three radio buttons.
 
public void BindDataTreeView(string field)
{
            try
            {
                MyTreeView.Items.Clear();
                conn.Open();
                SqlCommand comm = new SqlCommand("SELECT " + field + " FROM Student", conn);
                dr = comm.ExecuteReader();
                while (dr.Read())
                {
                    MyTreeView.Items.Add(dr.GetValue(0).ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                conn.Close();
            }
}

The above function will store the values of the given field into the TreeView from the database at runtime.

One more thing to keep in mind is that before adding new items you must clear your TreeView otherwise it will append the new items into TreeView everytime.

private void RBStudId_Checked(object sender, RoutedEventArgs e)
{
BindDataTreeView("StudId");
}

In the above code it will call the function which will store the values into the TreeView from the database at runtime and in that function when you call it you must pass the argument as a field name which you want to display into the TreeView from the database.

Here on the "Student Id" radio button it will call the function & pass the field name as "StudId", so it will add student id into the TreeView from the database.

Main Code : 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.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;
using System.Data.SqlClient;
using System.Data;
 
namespace WPFAllDatabaseOperationApplication
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
   
    public partial class MainWindow : Window
    {
        SqlConnection conn = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True;User Instance=True"
);
        SqlDataReader dr;
       
 public MainWindow()
        {
            InitializeComponent();
        }
       
 /// <summary>
        /// Bind the Values into Treeview
        /// </summary>
        /// <param name="field">Pass Feildname from the database to display in treeview</param>
        public void BindDataTreeView(string field)
        {
            try
            {
                MyTreeView.Items.Clear();
                conn.Open();
                SqlCommand comm = new SqlCommand("SELECT " + field + " FROM Student", conn);
                dr = comm.ExecuteReader();
                while (dr.Read())
                {
                    MyTreeView.Items.Add(dr.GetValue(0).ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            BindMyData();
            //Here by default it will display Student Name when window will be loaded...
            BindDataTreeView("StudName");
        }
 
       private void RBStudId_Checked(object sender, RoutedEventArgs e)
       {
           BindDataTreeView("StudId");
       }
 
       private void RBStudResult_Checked(object sender, RoutedEventArgs e)
       {
           BindDataTreeView("StudResult");
       }

       private void RBStudName_Checked(object sender, RoutedEventArgs e)
       {
           BindDataTreeView("StudName");
       }
    }
}

See the Output In the Images Below:

WPFTreeview1.JPG

In the same way depending on the selected radio button it will display the values into the Treeview:

WPFTreeview2.JPG
 

WPFTreeview3.JPG

Up Next
    Ebook Download
    View all
    Learn
    View all