2010年12月7日 星期二

構建DataSet實例

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;


namespace datatable
{
class Program
{
static void Main(string[] args)
{
DataTable table1 = new DataTable("Student");
table1.Columns.Add("ID",typeof (int));
table1.Columns.Add("Name",typeof (String ));
table1.Columns.Add("Sex",typeof (string ));

table1.Columns[0].Unique = true;
table1.Columns[0].AutoIncrement = true;
table1.Columns[0].AutoIncrementSeed = 10;
table1.Columns[0].AutoIncrementStep = 10;

DataRow row1 = table1.NewRow();
row1[0] = 001;
row1[1] = "Jam";
row1["Sex"] = "Man";
table1.Rows.Add(row1 );
DataRow row2 = table1.NewRow();
row2[0] = 002;
row2[1] = "Luch";
row2["Sex"] = "Woman";
table1.Rows.Add(row2);

DataTable table2 = new DataTable("Address");
table2.Columns.Add("ID",typeof (int));
table2.Columns.Add("Address");
table2.Columns.Add("TelePhone",typeof (string ));

DataRow row3 = table2.NewRow();
row3["ID"] =1;
row3[1] = "BeJing";
row3[2] = 13000001234;
table2.Rows.Add(row3 );

ForeignKeyConstraint foreignkey = new ForeignKeyConstraint(table1 .Columns [0],table2.Columns [0]);
foreignkey.DeleteRule = Rule.Cascade;
foreignkey.UpdateRule = Rule.Cascade ;
table2.Constraints.Add(foreignkey);
// table1.PrimaryKey = new DataColumn[] { table1.Columns[0], table1.Columns[1] };


DataRow row4 = table2.NewRow();
row4["ID"] = 2;
row4[1] = "ShangHai";
row4[2] = 13888884567;
table2.Rows.Add(row4);

DataSet dataset = new DataSet();

dataset.Tables.Add(table1 );
dataset.Tables.Add(table2);


foreach (DataRow row in table1.Rows)
{
for (int i = 0; i < table1.Columns.Count; i++)
Console.Write(row [i]+" ");
Console.WriteLine();
}
Console.WriteLine();
foreach (DataRow row in table2.Rows)
{
for (int i = 0; i < table2.Columns.Count; i++)
Console.Write(row[i]+" ");
Console.WriteLine();
}


Console.WriteLine();
Console.WriteLine();

//table1.Rows[0][0] = 6;
//table1.Rows.RemoveAt(1);

foreach (DataRow row in table1.Rows)
{
for (int i = 0; i < table1.Columns.Count; i++)
Console.Write(row[i] + " ");
Console.WriteLine();
}
Console.WriteLine();
foreach (DataRow row in table2.Rows)
{
for (int i = 0; i < table2.Columns.Count; i++)
Console.Write(row[i] + " ");
Console.WriteLine();
}
Console.Read();

}
}
}

沒有留言:

張貼留言