2/9/10

How to use DataSet

This topic for who work with asp.net C#
This topic i saw before in a project and i searched internet and reach this result.
To work with dataset you need the following things:
we will assume that we work in disconnected mode so we will use sqldataAdapter object.
note(you can use any provider you want like oleDB or odbc)
1-need an object of sqlConnection to set connection settings:
SqlConnection con = new SqlConnection();
con.ConnectionString =
"Data Source=yourServerName Initial Catalog=yourDataBaseName;
Integrated Security=true";
2- need an object of SqlDataAdapter
SqlDataAdapter dAdapter =
new SqlDataAdapter("SELECT * FROM Database'sTableName",con);
//(put your table name you to select from it)
3-need an object of dataset to save data in it (dataset will be cached in memory)
DataSet ds = new DataSet();
4-you must fill the dataset with the returned result from dataAdapter like this
dAdapter.fill(ds);
//unitl now you just put your data in data set next step is to insert in it new record and then update database with this inserted record
5-need an object of SqlCommand
string insertStr = string.format("INSERT INTO tableName (col1,col2,col3) VALUES
('{0}','{1}','{2}') ",value1,value2,value3);
//or you may use parameters
SqlCommand insertCmd = new SqlCommand(insertStr, con);
//assign insert command to our adapter
dAdapter.insertCommand = insertCmd;
6-need object of DataTable to assign to it the table in dataset
DataTable dt = ds.Tables[0];//Or ds.Tables["TableName"];
7-need newRow Object
DataRow newRow = dt.NewRow();
//assign to this row the values that you inserted before in the insert command
newRow["colName"] = value1;
newRow["colName"] = value2;
newRow["colName"] = value3;
8-Add this Row to the table in the DataSet
ds.Tables[0].Rows.Add(newRow);
9-Finally update your database with dataset
dAdapter.update(ds,"TableNameThat you will Update");
I hope This information to be has value for any one who need it
i will write any problem that i will see and its solution to share it with others

Thanks
Mohammed Shaaban
Software Developer
MarefaTech Co
Egypt Cairo

No comments:

Post a Comment