How to Store Temporary Information in Table Like Format in C#?

In C#, the DataTable class is included in the System. Data namespace serves to represent a table of data stored in memory. This class enables the creation, manipulation, and interaction with data that mirrors the format of a relational database table consisting of rows and columns. It is frequently utilized in applications to temporarily store data obtained from a database or for processing data in memory. This is beneficial when there is a need to enhance the fundamental DataTable by incorporating specific functionalities, such as a predefined schema (columns) or tailored methods for data manipulation.

Advantages of this Methodology

  1. Tailored Functionality: It is possible to enhance DataTable by incorporating methods and constraints that are unique to the domain of your application.
  2. Established Schema: The subclass can specify particular columns and primary keys, thereby minimizing the necessity to duplicate schema definitions across your codebase.
  3. Enhanced Type Safety: By consolidating the logic within a class, you improve the maintainability and type safety of your code.

Detailed Example in Sequential Steps

Step 1. Develop the Base Class that Derives from DataTable.

The base class will be responsible for initializing the DataTable, such as establishing columns. Additionally, you may incorporate shared methods or logic that can be utilized by subclasses.

using System.Data;
using System.Windows;

namespace DatatableStructureExample
{
    internal class StudentBaseTable : DataTable
    {
        string rowString = string.Empty;

        public StudentBaseTable(string tableName) : base(tableName)
        {
            // Set up the columns within the base class.
            InitializeColumns();
        }

        // A procedure for setting up shared columns.
        protected virtual void InitializeColumns()
        {
            // Establish the standard columns that will be utilized by all derived classes.
            this.Columns.Add("UserId", typeof(int));
            this.Columns.Add("UserName", typeof(string));
        }

        // Procedure for establishing the primary key column.
        public void SetPrimaryKey(string columnName)
        {
            this.PrimaryKey = new DataColumn[] { this.Columns[columnName] };
        }
    }
}

Step 2. Develop the Derived Class that Specifies a Particular Table.

The derived class (for instance, StudentInformationTable) will establish specific columns for the data table and may incorporate supplementary methods for managing StudentInformationTable data.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatatableStructureExample
{
    internal class StudentInformationTable : StudentBaseTable
    {
        public StudentInformationTable(string tableName) : base(tableName)
        {
            this.Columns.Add("UserAge", typeof(int));
            this.Columns.Add("UserAddress", typeof(string));
            this.SetPrimaryKey("UserId");
        }

        // A procedure for incorporating a student into the table.
        public void AddStudentInformation(int userId, string userName, int userAge, string userAddress)
        {
            DataRow row = this.NewRow();
            row["UserId"] = userId;
            row["UserName"] = userName;
            row["UserAge"] = userAge;
            row["UserAddress"] = userAddress;
            this.Rows.Add(row);
        }

        // A procedure for terminating a student information based on their identification number.
        public void RemoveStudentInformationById(int id)
        {
            DataRow row = this.Rows.Find(id);
            if (row != null)
            {
                this.Rows.Remove(row);
            }
        }
    }
}

Step 3. The StudentInformationTable class can now be utilized within your application to instantiate the StudentInformationTable table, incorporate StudentInformationTable records, and display them. I am utilizing a WPF application to work with a DataTable, allowing you to meet your requirements in your own manner.

UI View

<Window x:Class="DatatableStructureExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DatatableStructureExample"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Grid>
        <StackPanel Margin="10" Orientation="Vertical">
            <!-- User ID -->
            <StackPanel Orientation="Horizontal" Margin="0,5">
                <TextBlock Text="User ID:" VerticalAlignment="Center" Width="100"/>
                <TextBox x:Name="UserIdTextBox" Width="200"/>
            </StackPanel>

            <!-- User Name -->
            <StackPanel Orientation="Horizontal" Margin="0,5">
                <TextBlock Text="User Name:" VerticalAlignment="Center" Width="100"/>
                <TextBox x:Name="UserNameTextBox" Width="200"/>
            </StackPanel>

            <!-- User Age -->
            <StackPanel Orientation="Horizontal" Margin="0,5">
                <TextBlock Text="User Age:" VerticalAlignment="Center" Width="100"/>
                <TextBox x:Name="UserAgeTextBox" Width="200"/>
            </StackPanel>

            <!-- User Address -->
            <StackPanel Orientation="Horizontal" Margin="0,5">
                <TextBlock Text="User Address:" VerticalAlignment="Center" Width="100"/>
                <TextBox x:Name="UserAddressTextBox" Width="200"/>
            </StackPanel>

            <!-- Remove Id -->
            <StackPanel Orientation="Horizontal" Margin="0,5">
                <TextBlock Text="Remove Id:" VerticalAlignment="Center" Width="100"/>
                <TextBox x:Name="RemoveIdTextBox" Width="200"/>
            </StackPanel>
        </StackPanel>

        <StackPanel Orientation="Horizontal">
            <Button x:Name="BtnCreateRow" Content="Create Row" Height="40" Width="200" Click="BtnCreateRow_Click" Margin="30,0,0,0"/>
            <Button x:Name="BtnDeleteRow" Content="Delete Row" Height="40" Width="200" Click="BtnDeleteRow_Click" Margin="20,0,0,0"/>
            <Button x:Name="BtnShowDetails" Content="Show Details" Height="40" Width="200" Click="BtnShowDetails_Click" Margin="20,0,0,0"/>
        </StackPanel>

        <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" Margin="10,252,10,10"/>
    </Grid>
</Window>

Appearance of the view

Appearance of the view

Code Behind Implementation

using System.Collections.ObjectModel;
using System.Data;
using System.Text;
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 DatatableStructureExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        StudentInformationTable studentInformation;
        private ObservableCollection<DataItemModel> dataItems = new ObservableCollection<DataItemModel>();

        public MainWindow()
        {
            InitializeComponent();
            studentInformation = new StudentInformationTable("StudentTable");
        }

        private void BtnCreateRow_Click(object sender, RoutedEventArgs e)
        {
            // Create an instance of StudentInformationTable
            studentInformation.AddStudentInformation(
                Convert.ToInt32(UserIdTextBox.Text), 
                UserNameTextBox.Text, 
                Convert.ToInt32(UserAgeTextBox.Text), 
                UserAddressTextBox.Text);
        }

        private void BtnDeleteRow_Click(object sender, RoutedEventArgs e)
        {
            studentInformation.RemoveStudentInformationById(Convert.ToInt32(RemoveIdTextBox.Text));
        }

        private void BtnShowDetails_Click(object sender, RoutedEventArgs e)
        {
            dataGrid.ItemsSource = null;

            if (dataItems.Count > 0)
            {
                dataItems.Clear();
            }

            foreach (DataRow item in studentInformation.Rows)
            {
                if (item != null)
                {
                    var dataItemModel = new DataItemModel
                    {
                        Column1 = item[0].ToString(),
                        Column2 = item[1].ToString(),
                        Column3 = item[2].ToString(),
                        Column4 = item[3].ToString()
                    };

                    // Add the item to the collection bound to the DataGrid
                    dataItems.Add(dataItemModel);
                }
            }

            dataGrid.ItemsSource = dataItems;
        }
    }
}

Step 4. Results of the implementation.

Implementation

  1. Create Row functionality: This feature is utilized to insert a new row into the DataTable.
  2. Delete Row Functionality: This feature is employed to eliminate any previously added item into the DataTable.
  3. Show Details Functionality: This feature is designed to present all rows that have been added to the Data Table.


Similar Articles