Hi i am working on creating sqlconnectivity class and i come across a problem when i tried to update the whole dataset after editing it in datagridview. Can Please anyone sugguest why i cant seem to abel to update my dataset. Here is my Class code which i used to fetch datset and update dataset.
public class clssql
{
#region private sqlvariabels
private static string _sqlconnectionstring;
private SqlDataAdapter _sqldataadapter;
private SqlCommand _sqlcommand;
private SqlConnection _sqlconnection;
private SqlCommandBuilder _sqlcommandbuilder;
private SqlTransaction _sqlTransaction;
private DataSet _ds;
private bool _Transctionbinded=false;
private string _errorstring;
#endregion
/// <summary>
/// Constructor for clssql
/// </summary>
public clssql()
{
_sqlconnectionstring = GenerateSQLConnectionString(false);
_sqlconnection = new SQLConnection(_sqlconnectionstring);
}
/// <summary>
/// BindsTransaction to the Object
/// </summary>
public void BindTransaction()
{
_Transctionbinded = true;
_sqlconnection.Open();
_sqlTransaction = _sqlconnection.BeginTransaction();
_sqlcommand.Transaction = _sqlTransaction;
}
/// <summary>
/// Releases the transaction
/// </summary>
public void ReleaseTransaction()
{
if (_errorstring=="")
{
_Transctionbinded = false;
_sqlTransaction.Commit();
_sqlconnection.Close();
}
else
{
}
_sqlTransaction = null;
}
/// <summary>
/// Generate sqlconnection string.
/// </summary>
/// <param name="hardcoded">set to true if you want hardcoded string and not from app.config generated</param>
/// <returns></returns>
public static string GenerateSQLConnectionString(bool hardcoded = false)
{
StringBuilder connstring = new StringBuilder();
if (hardcoded)
{
return @"Data Source=MAYA-PC\SQLExpress;Initial Catalog=BankDB;Persist Security Info=True;User ID=sa;Password=sql123";
}
else
{
try
{
connstring.Append("Data Source=" + ConfigurationManager.AppSettings["DataSource"] + ";");
connstring.Append("Initial Catalog=" + ConfigurationManager.AppSettings["InitialCatalog"] + ";");
connstring.Append("Persist Security Info=True;");
connstring.Append("User ID=" + ConfigurationManager.AppSettings["UserID"] + ";");
connstring.Append("Password=" + ConfigurationManager.AppSettings["Password"] + ";");
return connstring.ToString();
}
catch (Exception)
{
throw;
}
}
}
/// <summary>
/// Executes an SQL Command Text.
/// </summary>
/// <param name="Query">Query to execute</param>
/// <returns>Returns the Number of Rows Affected</returns>
public int ExecuteNonQuery(string Query)
{
try
{
int rec;
if (_Transctionbinded)
{
//Do Nothing
}
else
{
_sqlconnection.Open();
}
//_sqlconnection = new SqlConnection(_sqlconnectionstring);
_sqlcommand.CommandText = Query;
_sqlcommand.CommandType = CommandType.Text;
rec = _sqlcommand.ExecuteNonQuery();
if (_Transctionbinded)
{
//Do Nothing
}
else
{
_sqlconnection.Close();
}
return rec;
}
catch (Exception ex)
{
if (_Transctionbinded)
{
_errorstring = ex.Message;
}
else
{
_sqlconnection.Close();
}
throw;
}
}
/// <summary>
/// Directly Executes an SQL Command
/// </summary>
/// <param name="_sqlcommand"></param>
/// <returns></returns>
public int ExecuteCommand(SqlCommand _sqlcommand)
{
try
{
int rec;
if (_Transctionbinded)
{
//Do Nothing
}
else
{
_sqlconnection.Open();
}
_sqlcommand.Connection = _sqlconnection;
rec =_sqlcommand.ExecuteNonQuery();
if (_Transctionbinded)
{
//Do Nothing
}
else
{
_sqlconnection.Close();
}
return rec;
}
catch (Exception ex)
{
if (_Transctionbinded)
{
_errorstring = ex.Message;
}
else
{
_sqlconnection.Close();
}
throw;
}
}
/// <summary>
/// Get Dataset From Query
/// </summary>
/// <param name="SelectQuery"></param>
/// <returns></returns>
public DataSet GetDataset(string SelectQuery)
{
try
{
if (_Transctionbinded)
{
//Do Nothing
}
else
{
_sqlconnection = new SqlConnection(_sqlconnectionstring);
_sqlconnection.Open();
}
_sqlcommand = new SqlCommand(SelectQuery, _sqlconnection);
_sqldataadapter = new SqlDataAdapter(_sqlcommand);
_sqlcommandbuilder = new SqlCommandBuilder(_sqldataadapter);
_ds = new DataSet();
_sqldataadapter.Fill(_ds);
if (_Transctionbinded)
{
//Do Nothing
}
else
{
_sqlconnection.Close();
}
return _ds;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Updates Dataset
/// </summary>
/// <param name="ds"></param>
/// <returns></returns>
public int UpdateDataset(DataSet ds)
{
int rec;
try
{
if (_Transctionbinded)
{
//Do Nothing
}
else
{
_sqlconnection.Open();
}
if (ds.HasChanges()) {
ds.AcceptChanges();
}
_sqldataadapter.UpdateCommand = _sqlcommandbuilder.GetUpdateCommand(true);
_sqldataadapter.InsertCommand = _sqlcommandbuilder.GetInsertCommand(true);
_sqldataadapter.DeleteCommand = _sqlcommandbuilder.GetDeleteCommand(true);
rec = _sqldataadapter.Update(ds);
if (_Transctionbinded)
{
//Do Nothing
}
else
{
_sqlconnection.Close();
}
return rec;
}
catch (Exception ex)
{
if (_Transctionbinded)
{
_errorstring = ex.Message;
}
else
{
_sqlconnection.Close();
}
throw;
}
}
}
Well i have putted my whole class here but The getdataset and update dataset are the only one that matters no need for transctions right now just for future refrences.
In the same Project when i tried this code the after editing datagridview the dataset was updated correctly. i tried and tried but dont understand why it works on the below code and doesnt work on above code..
private void LoadClick(object sender, EventArgs e)
{
string connectionString = @"Data Source=MAYA-PC\SQLExpress;Initial Catalog=CrystalTutorial;Persist Security Info=True;User ID=sa;Password=sql123";
string sql = "Select * From Customer_Orders";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
sCommand = new SqlCommand(sql, connection);
sAdapter = new SqlDataAdapter(sCommand);
sBuilder = new SqlCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "Stores");
sTable = sDs.Tables["Stores"];
connection.Close();
dataGridView1.DataSource = sDs.Tables["Stores"];
dataGridView1.ReadOnly = true;
btnsave.Enabled = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void new_btn_Click(object sender, EventArgs e)
{
dataGridView1.ReadOnly = false;
btnsave.Enabled = true;
btnnew.Enabled = false;
btndelete.Enabled = false;
}
private void delete_btn_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
sAdapter.Update(sTable);
}
}
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
btnsave.Enabled = false;
btnnew.Enabled = true;
btndelete.Enabled = true;
}
You should not call the AcceptChanges method before the Update. You will find the explanation to this in the Order of using AcceptChanges and TableAdapter.Update thread.