Tuesday, October 28, 2008

Insert data using dataset

In ADO.net we can insert data into database using with Dataset. this is very use full for insert update detele, no need to write storeprocedure for data insertion. we can also insert multiple rows in single connection.

Code Example:
SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
DataTable objTable;
DataRow objRow;
SqlDataAdapter objDataAdapter=new SqlDataAdapter();
DataSet objDataSet = new DataSet();
SqlCommand objCommand = new SqlCommand();
objCommand.Connection = cn;
objCommand.CommandText = "Select * from table_1 Where 1=2";
objDataAdapter.SelectCommand = objCommand;
//** SqlCommandBuilder class's ability to auto-
//** generate Insert command from the SELECT command.
SqlCommandBuilder autogen = new SqlCommandBuilder(objDataAdapter);
objDataAdapter.Fill(objDataSet, "table_1");
objTable = objDataSet.Tables[0];
objRow = objTable.NewRow();

objRow[1] = "name";

objRow[2] = "Address";

objDataAdapter.Update(objDataSet, tableName);
returnVal = true;
return returnVal;
catch(Exception ex)
throw ex;

No comments: