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);
}
}
}
SubashPosted Sep 7, 2016, 4:01 AM
Good
suderson sarathyPosted Feb 26, 2010, 4:33 AM
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
dinesh kumarPosted Jul 9, 2009, 12:00 PM
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.
Benjamin Oreste NunezeditedPosted Jan 14, 2009, 8:07 PMEdited Jan 14, 2009, 8:09 PM
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?
balasundaram rengasamyPosted Mar 3, 2008, 1:28 AM
i want to gridviewupdate command for sql
Cosmin 0Posted Jul 18, 2006, 2:51 PM
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()); } }
YogesheditedPosted Apr 1, 2006, 4:54 AMEdited Apr 1, 2006, 5:52 AM
Its very good Article