Tuesday, September 27, 2011

Tuesday 9.27.11

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sqlConnectString = @"Data Source=Alfred-PC\SQLExpress;" +
"Integrated Security=SSPI; Initial Catalog=AdventureWorks;";

string sqlSelect = "SELECT ContactID, FirstName, LastName FROM Person.Contact " +
"WHERE ContactID BETWEEN 10 AND 13";

//create a data adapter
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);

//fill a data table using DataAdapter
DataTable dt1 = new DataTable();
da.Fill(dt1);

//output the rows from the table
Console.WriteLine("--foreach loop over DataRowCollection (DataTable 1)---");
foreach (DataRow row in dt1.Rows)
{
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}", row["ContactID"], row["FirstName"], row["LastName"]);
}
//create and fill the DataRow array
DataRow[] dra = new DataRow[dt1.Rows.Count];
dt1.Rows.CopyTo(dra, 0);

Console.WriteLine("\n--for loop over DataRow array---");
for (int i = 0; i < dra.Length; i++)
{
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}", dra[i].Field("ContactID"), dra[i].Field("FirstName"), dra[i].Field("LastName"));
}

//filling a DataTable from the DataRow array using CopyToDataTable()
DataTable dt2 = dra.CopyToDataTable();
//output the rows from the table
Console.WriteLine("\n---foreach loop over DataRowCollection (DataTable 2)---");
foreach (DataRow row in dt2.Rows)
{
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}", row["ContactID"], row["FirstName"], row["LastName"]);
}

//filling a DataTable from the DataRow array using CopyToDataTable(DataTable, LoadOption)
DataTable dt3 = dt1.Clone();
dra.CopyToDataTable(dt3, LoadOption.Upsert);
Console.WriteLine("\n----foreach loop over DataRowCollection (DataTable 3)---");
foreach (DataRow row in dt3.Rows)
{
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName={2}", row["ContactID"], row["FirstName"], row["LastName"]);
}

}
}
}

No comments: