ARTICLE

Update Database using DataSet

Posted by Ashish Singhal Articles | How do I February 06, 2006
In this article, we will see how to update a database using a Data Adapter's Update method using C# and ADO.NET.
Reader Level:

Here we are going to see how to update database using DataSet and SqlDataAdapter.

using System;

using System.Windows.Forms;

using System.Data;

using System.Data.SqlClient; 

namespace UpdateDatabase

{ 

          public class TestDataSet : System.Windows.Forms.Form

           

                    private System.Windows.Forms.DataGrid dataGrid1;

                    private System.Windows.Forms.Button btnLoad;

                    private System.Windows.Forms.Button btnUpdate;

                    private DataSet ds;

                    private SqlDataAdapter adap;

                    private SqlConnection con;

                    private System.Windows.Forms.Label lblTitle;

                    private System.Windows.Forms.TextBox txtTitle; 

                    private System.ComponentModel.Container components = null;

                    public TestDataSet()

                    {

                             InitializeComponent();

                             con = new SqlConnection("server=.;uid=sa;pwd=test;database=test");} 

                    /// <summary> 

                    /// Clean up any resources being used. 

                    /// </summary> 

                    protected override void Dispose( bool disposing )

                    {

 

                             if( disposing )

                             {

                                       if (components != null)

                                       {

                                                components.Dispose();

                                       }

                             }

                             base.Dispose( disposing );

                    }

 

                    #region Windows Form Designer generated code

 

                    /// <summary>

                    /// Required method for Designer support - do not modify

                    /// the contents of this method with the code editor.

                    /// </summary>

 

                    private void InitializeComponent()

                    {

 

                             this.dataGrid1 = new System.Windows.Forms.DataGrid();

                             this.btnUpdate = new System.Windows.Forms.Button();

                             this.btnLoad = new System.Windows.Forms.Button();

                             this.txtTitle = new System.Windows.Forms.TextBox();

                             this.lblTitle = new System.Windows.Forms.Label();

                             ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();

                             this.SuspendLayout();

 

                             //

                             // dataGrid1

                             //  

                             this.dataGrid1.DataMember = "";

                             this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;

                             this.dataGrid1.Location = new System.Drawing.Point(16, 80);

                             this.dataGrid1.Name = "dataGrid1";

                             this.dataGrid1.Size = new System.Drawing.Size(568, 280);

                             this.dataGrid1.TabIndex = 0;

 

                             //

                             // btnUpdate

                             //  

                             this.btnUpdate.Location = new System.Drawing.Point(176, 369);

                             this.btnUpdate.Name = "btnUpdate";

                             this.btnUpdate.Size = new System.Drawing.Size(112, 23);

                             this.btnUpdate.TabIndex = 1;

                             this.btnUpdate.Text = "Update Title";

                             this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);

 

                             //

                             // btnLoad

                             //  

                             this.btnLoad.Location = new System.Drawing.Point(504, 56);

                             this.btnLoad.Name = "btnLoad";

                             this.btnLoad.TabIndex = 2;

                             this.btnLoad.Text = "Load";

                             this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click);

 

                             //

                             // txtTitle

                             //  

                             this.txtTitle.Location = new System.Drawing.Point(64, 372);

                             this.txtTitle.Name = "txtTitle";

                             this.txtTitle.TabIndex = 3;

                             this.txtTitle.Text = "";

 

                             //

                             // lblTitle

                             //  

                             this.lblTitle.AutoSize = true;

                             this.lblTitle.Location = new System.Drawing.Point(16, 376);

                             this.lblTitle.Name = "lblTitle";

                             this.lblTitle.Size = new System.Drawing.Size(26, 16);

                             this.lblTitle.TabIndex = 4;

                             this.lblTitle.Text = "Title";

 

                             //

                             // TestDataSet

                             //  

                             this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

                             this.ClientSize = new System.Drawing.Size(616, 438);

                             this.Controls.Add(this.lblTitle);

                             this.Controls.Add(this.txtTitle);

                             this.Controls.Add(this.btnLoad);

                             this.Controls.Add(this.btnUpdate);

                             this.Controls.Add(this.dataGrid1); 

                             this.Name = "TestDataSet";

                             this.Text = "Data";

                             ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();

                             this.ResumeLayout(false);

 

                    }

 

                    #endregion 

                    /// <summary>

                    /// The main entry point for the application.

                    /// </summary>

 

                    [STAThread]

                    static void Main()

                    {

                             Application.Run(new TestDataSet());

                    }

 

                    private void btnLoad_Click(object sender, System.EventArgs e)

                    {

                             LoadData();

                     

                    //Load data from database make sure we are fetching primarykey too so we could use adapter

                    update method

                    //on dataset because commandbuilder will create command on that primary key.

                    //Commands will be created as it see rowstate of dataset table's row's rowstate.

                    private void LoadData()

                    {

                             if(ds != null)

                                       ds.Clear();

                             adap = new SqlDataAdapter("select id,title, description from testtable", con);

                             ds = new DataSet();

                             adap.Fill(ds);

                             dataGrid1.DataSource = ds.Tables[0];

                    } 

                    //This click will update one of the field in the database using adapter update() method on

                    dataset.

                    private void btnUpdate_Click(object sender, System.EventArgs e)

                    {

                             SqlCommandBuilder com = new SqlCommandBuilder(adap);

                             foreach(DataRow dr in ds.Tables[0].Rows)

                                       dr["title"] = txtTitle.Text;

                             adap.Update(ds);

                    } 

          }

}

Login to add your contents and source code to this article
post comment
     

I just wanna know the steps to update a dataset and then from their i wanna update the database.. And moreover I've to use the delegates....

I've 50 rows each contains a checkbox.. If am clicking 5 check boxes, all the five rows have to updated in the dataset and then from database. Can any one help me out of this..

Please..

Thanks in advance

Posted by suderson sarathy Feb 26, 2010

Hi ashish,
My name is dinesh and i m doing a project on cyber cafe management software solution. I used dataset and dataadapter to connect and updata database like you did above but it made changes at first but now it retrieves the data but doesn't write changes back to database and it shows success, when i look at database it contains the old values.Please help me. Could you assist me in my project?
Thank you.

Posted by dinesh kumar Jul 09, 2009

I tried using the sqlCommandBuilder but I get an exception
when I call the adapter's Update method. The exception
I'm getting is:

"Dynamic SQL generation for the UpdateCommand is not supported
against a SelectCommand that does not return any key
column information."

I have specified my primary key in my select statement
and even tried "SELECT * FROM TABLE..." but still no luck.

When I went to this msdn website: http://msdn.microsoft.com/en-us/library/ms971491.aspx

I learned that to use the CommandBuilder, one of its
requirements is that there should be no whitespaces/spaces
in one of your columns (mine has), otherwise you can't use the CommandBuilder.

Is there another way to do an update?

Posted by Benjamin Oreste Nunez Jan 14, 2009

i want to gridviewupdate command for sql

Posted by balasundaram rengasamy Mar 03, 2008

My issue is the update of a dataBase table with a dataSet table as a parameter using C#.
Below is the function I used in my code ---> verry simple.

I noticed that in line :updates = da.Update(tmpDS, tableName) ,updates variable is 0 ,so no update possible.
Perhaps this is not the way to do the update.
IF you can help me with some hints , thanks in advance.

 

public DataSet dsUpdateData(DataSet ds, string tableName, string ConnectionString)
        {
            //use  a Local temporary dataset
            DataSet tmpDS = new DataSet();
            try
            {
                //dataAdapter object
                SqlDataAdapter da = new SqlDataAdapter(SQLQuery + tableName, ConnectionString);
               
                //update dataset with records from DataBase
                int updates = da.Fill(tmpDS,tableName);

                //update tmpDS with the parameter dataset
                foreach (DataRow dataRow in ds.Tables[tableName].Rows)
                {
                    tmpDS.Tables[tableName].ImportRow(dataRow);
                    tmpDS.Tables[tableName].AcceptChanges();
                }

                //update the dataBase<<<---- here I get now update
                updates = da.Update(tmpDS, tableName);

                return tmpDS;
            }
            catch (Exception ex)
            {
               Debug.WriteLine(ex.ToString());
            }
        }

Posted by Cosmin Jul 18, 2006
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter