In C#, What Is The Process Of Creating A DataTable And Subsequently Inserting Rows Into It?

To create a DataTable in C#, you can follow these steps:

  1. Import the System.Data namespace.
  2. Create a new instance of the DataTable class.
  3. Define the structure of the DataTable by adding DataColumn objects.
  4. Add rows to the DataTable using the NewRow method and then populating the data in each column of the row.
  5. Add the rows to the DataTable using the Rows collection.

Here’s an example:

using System;
using System.Data;

class Program
{
    static void Main()
    {
        // Create a new instance of DataTable
        DataTable table = new DataTable("MyTable");

        // Define the structure of the DataTable by adding DataColumn objects
        DataColumn column1 = new DataColumn("Id", typeof(int));
        DataColumn column2 = new DataColumn("Name", typeof(string));

        // Add the DataColumn objects to the DataTable
        table.Columns.Add(column1);
        table.Columns.Add(column2);

        // Add rows to the DataTable
        DataRow row1 = table.NewRow();
        row1["Id"] = 1;
        row1["Name"] = "John Doe";
        table.Rows.Add(row1);

        DataRow row2 = table.NewRow();
        row2["Id"] = 2;
        row2["Name"] = "Jane Smith";
        table.Rows.Add(row2);

        // Print the contents of the DataTable
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine("Id: {0}, Name: {1}", row["Id"], row["Name"]);
        }
    }
}

In this example, we create a DataTable called "MyTable" with two columns "Id" of type int and "Name" of type string. We then add two rows to the DataTable with their respective values for each column. Finally, we iterate over the rows and print their content.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!