September 19, 2024

How to create dynamic DataTable in C#?

In programs DataTable is used for various purposes. It is mainly used for storage. We can creates DataTables in different ways. This article describes how to add values dynamically in DataTable in C#.

DataTable is a powerful technology or idea to store data in memory.  We can also use the data of DataTable in our data source for our control like GridView Or DataGridView.
In C# we can create a DataTable dynamically. That means we can add columns or rows according to our needs.

Let us consider a Students table which has three columns, StudentID, StudentName,Phone and a Marks table which has also three columns StudentID, Subject, Mark. Suppose we have some data inserted into the both tables. In Marks table Subjects are different for each student (one has physic, math and another one has math, chemistry, English).

Our goal is to display all the students ID, Names, Phone and their Subject wise marks in a single table.
Following C# code will generate that type of DataTable.

DataTable oDataTable1 = new DataTable();
DataTable oDataTable2 = new DataTable();

oDataTable1 = SelectDataTable("SELECT StudentID,StudentName,Phone FROM dbo.Students");
oDataTable2 = SelectDataTable("SELECT StudentID,Subject,Mark FROM dbo.Marks");

string Subject = string.Empty;
string Mark = string.Empty;
string StudentID = string.Empty;

for (int i = 0; i < oDataTable2.Rows.Count; i++)
{
    Subject = oDataTable2.Rows[i]["Subject"].ToString();
    Mark = oDataTable2.Rows[i]["Mark"].ToString();
    StudentID = oDataTable2.Rows[i]["StudentID"].ToString();

    if (!oDataTable1.Columns.Contains(Subject))
    {
        oDataTable1.Columns.Add(Subject, typeof(Int16));

        DataRow[] oDataRow = oDataTable1.Select("StudentID=" + StudentID + "");
        for (int j = 0; j < oDataRow.Length; j++)
        {
            oDataRow[j][Subject] = Mark;
        }
    }

}

That’s all about dynamic data table.

Rashedul Alam

I am a software engineer/architect, technology enthusiast, technology coach, blogger, travel photographer. I like to share my knowledge and technical stuff with others.

View all posts by Rashedul Alam →

One thought on “How to create dynamic DataTable in C#?

Leave a Reply

Your email address will not be published. Required fields are marked *