Create a DataSet Programmatically - CSharp Database

CSharp examples for Database:DataSet

Description

Create a DataSet Programmatically

Demo Code


using System;/*from w  ww . j  av a  2s  . co m*/
using System.Data;

class MainClass
    {
        static void Main(string[] args)
        {
            DataSet dataset = new DataSet();

            DataTable table = new DataTable("Regions");
            dataset.Tables.Add(table);

            table.Columns.Add("RegionID", typeof(int));
            table.Columns.Add("RegionDescription", typeof(string));

            string[] regions = { "Eastern", "Western", "Northern", "Southern" };
            for (int i = 0; i < regions.Length; i++)
            {
                DataRow row = table.NewRow();
                row["RegionID"] = i + 1;
                row["RegionDescription"] = regions[i];
                table.Rows.Add(row);
            }

            foreach (DataColumn col in table.Columns)
            {
                Console.WriteLine("Column: {0} Type: {1}", col.ColumnName, col.DataType);
            }
            foreach (DataRow row in table.Rows)
            {
                Console.WriteLine("Data {0} {1}", row[0], row[1]);
            }
            DataRow newrow = table.NewRow();
            newrow["RegionID"] = 5;
            newrow["RegionDescription"] = "Central";
            table.Rows.Add(newrow);

            table.Rows[0]["RegionDescription"] = "North Eastern";

            Console.WriteLine("\nData in (modified) table");
            foreach (DataRow row in table.Rows)
            {
                Console.WriteLine("Data {0} {1}", row[0], row[1]);
            }
        }
    }

Result


Related Tutorials