How do I create a temporary DataTable and merge it into a DataSet in C#?

using System;
using System.Data;

public class Program {
    public static void Main() {
        // 1. Create a Master DataSet
        DataSet masterDataSet = new DataSet("BusinessDataSet");
        
        // 2. Create a Temporary DataTable
        DataTable tempTable = new DataTable("TempEmployees");
        
        // Define columns for the temp table
        tempTable.Columns.Add("ID", typeof(int));
        tempTable.Columns.Add("Name", typeof(string));
        tempTable.Columns.Add("Role", typeof(string));
        
        // 3. Add sample data to the temporary table
        tempTable.Rows.Add(1, "Alice", "Developer");
        tempTable.Rows.Add(2, "Bob", "Architect");
        
        Console.WriteLine("Temporary Table created with " + tempTable.Rows.Count + " rows.");
        
        // 4. Merge the DataTable into the DataSet
        // The Merge method combines the schema and data
        masterDataSet.Merge(tempTable);
        
        // 5. Verify the results
        Console.WriteLine("\nDataSet now contains table: " + masterDataSet.Tables[0].TableName);
        
        foreach (DataRow row in masterDataSet.Tables["TempEmployees"].Rows) {
            Console.WriteLine($"ID: {row["ID"]} | Name: {row["Name"]} | Role: {row["Role"]}");
        }
    }
}

0 Comments:

Post a Comment