Write the changes in a DataSet using a DbDataAdapter : DbDataAdapter « ADO.net Database « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UpdatingDataSet" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <title>Updating a DataSet</title>
<body>
   <form id="form1" runat="server">
      <div id="container">
         <h1>Updating a DataSet</h1>
      <h2>Authors</h2>
      <asp:GridView ID="grdAuthors" runat="server" />
      
         <asp:Label ID="labMsg" runat="server" />
         
      </div>
   </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.OleDb;

public partial class UpdatingDataSet : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
      connString += Server.MapPath("~/App_Data/Book.mdb") + ";";

      DataSet ds = new DataSet();

      try
      {
         OleDbConnection conn = new OleDbConnection(connString);

         OleDbDataAdapter adapter = new OleDbDataAdapter();

         string sqlSelect = " SELECT * FROM Authors";
         OleDbCommand cmdSelect = new OleDbCommand(sqlSelect, conn);
         adapter.SelectCommand = cmdSelect;

         string sqlInsert = "INSERT INTO Authors (AuthorName)";
         sqlInsert += "VALUES (@name) ";

         OleDbCommand cmdInsert = new OleDbCommand(sqlInsert, conn);
         OleDbParameter param = new OleDbParameter("@name",OleDbType.VarChar);
         param.SourceColumn = "AuthorName";
         param.SourceVersion = DataRowVersion.Current;

         cmdInsert.Parameters.Add(param);
         adapter.InsertCommand = cmdInsert;

         adapter.Fill(ds, "AuthorsTable");

         DataRow dr1 = ds.Tables["AuthorsTable"].NewRow();
         dr1["AuthorName"] = "R";
         ds.Tables["AuthorsTable"].Rows.Add(dr1);

         DataRow dr2 = ds.Tables["AuthorsTable"].NewRow();
         dr2["AuthorName"] = "A";
         ds.Tables["AuthorsTable"].Rows.Add(dr2);

         adapter.Update(ds, "AuthorsTable");

         grdAuthors.DataSource = ds.Tables["AuthorsTable"].DefaultView;
         grdAuthors.DataBind();
      }
      catch (Exception ex)
      {
         labMsg.Text = "Error occurred accessing the database";
         labMsg.Text += "<br/>" + ex.Message;
      }
   }
}








18.32.DbDataAdapter
18.32.1.Write the changes in a DataSet using a DbDataAdapter