Search This Blog

Sunday, January 17, 2010

Adding Primary Key to Table loaded in Dataset in C#:

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

namespace Finding_Records
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Initial Catalog=sangram;Data Source=(local)");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from course", con);
SqlCommandBuilder sbuilder = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "course");

//Here we define Object to hod Primary key
DataColumn[] keys = new DataColumn[1];
keys[0] = ds.Tables[0].Columns["cno"];
ds.Tables[0].PrimaryKey = keys;

DataRow findrow = ds.Tables[0].Rows.Find("28");

if (findrow == null)
{
Console.WriteLine("No row with primay key column value 28 is Found");
Console.WriteLine("We can Add the row without violation of Primary key constraint");

DataRow drow = ds.Tables[0].NewRow();
drow[0] = 28;
drow[1] = "Advanced Java";
drow[2] = 3;
drow[3] = 5000;

ds.Tables[0].Rows.Add(drow);
}
else
{
Console.WriteLine("Row Found");
}
da.Update(ds, "course");
con.Close();
Console.ReadKey();
}
}
}

No comments:

Post a Comment