Friday, July 8, 2011

Updating specific row in a DataSet ( C# and asp.net )

This is a tutorial on updating a specific row in a DataSet. For this example, I will be performing the updation on a DataSet that exists in the Cache.

For this particular example, let us consider a DataSet which contains a Table of Employee Data.

Step 1: Populating the DataSet

DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter("GETREPORTINGEMPLOYEES",conn);
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
ad.SelectCommand.Parameters.AddWithValue("@MANAGERID", MANAGERID);
ad.Fill(ds, "GETREPORTINGEMPLOYEES");

Step 2: Add the DataSet to Cache

Cache.Insert("REPORTINGEMPLOYEES", ds, null , DateTime.Now.AddMinutes(60), TimeSpan.Zero);

Step 3: Retreive DataSet from Cache

DataSet ds = (DataSet)Cache["REPORTINGEMPLOYEES"];

Step 4: Perform Update

//Searching the DataSet using column names
//The column names are what our sql stored procedure returns
//For ex: SELECT ID, NAME, PHONE, RANK FROM EMPLOYEE
//Say I want to update the Rank where the employee ID is 2340873
//First I get the DataRow[]
DataRow[] EmpRow = ds.Tables[0].Select("ID = '2340873'");
//Then I update the Rank as I know it is the 3rd column in the Row
//I know it is the 3rd row because of the SQL query which returns 4 columns
EmpRow[0][3] = 4;

Cheers

No comments:

Post a Comment