I'm learning programmersheaven E-book about C# School at Chapter 12 (Data Access using ADO.Net) and I get Error Reporting : "Concurrency violation: the UpdateCommand affected 0 of the expected 1 records". Please help me, this is my source code:
// Update database in Ms Access
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
namespace ADONet
{
public partial class Form1 : Form
{
private OleDbConnection connection;
private OleDbDataAdapter dataAdapter;
private DataSet dataSet;
private DataTable dataTable;
public Form1()
{
InitializeComponent();
}
// Load from database
private void btnLoad_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + @"D:\C#\csharp_ebook mirror.pdf\12\adapter.mdb";
try
{
connection = new OleDbConnection(connectionString);
string commandString = "SELECT * FROM Customers";
dataAdapter = new OleDbDataAdapter(commandString, connection);
dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Customers");
dataTable = dataSet.Tables["Customers"];
// for display CustomerID and CompanyName in TextBox
string data = dataTable.Rows[0]["CustomerID"].ToString();
txbCustomerID.Text = data;
data = dataTable.Rows[0]["CompanyName"].ToString();
txbCompanyName.Text = data;
InitializeCommands();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
this.Cursor = Cursors.Default;
}
// Save to database
private void btnSave_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
DataRow row = dataTable.Rows[0];
row.BeginEdit();
row["CompanyName"] = txbCompanyName.Text; // Update from TextBox
row.EndEdit();
dataAdapter.Update(dataSet, "Customers"); // Error happened here!!! please help me...
dataSet.AcceptChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
this.Cursor = Cursors.Default;
}
private void InitializeCommands()
{
// Preparing Insert SQL Command
dataAdapter.InsertCommand = connection.CreateCommand();
dataAdapter.InsertCommand.CommandText =
"INSERT INTO Customers " +
"(CustomerID, CompanyName) " +
"VALUES (?, ?)";
AddParams(dataAdapter.InsertCommand, "CustomerID", "CompanyName");
// Preparing Update SQL Command
dataAdapter.UpdateCommand = connection.CreateCommand();
dataAdapter.UpdateCommand.CommandText =
"UPDATE Customers SET " +
"CompanyName=? " +
"WHERE CustomerID=?";
AddParams(dataAdapter.UpdateCommand, "CustomerID", "CompanyName");
// Preparing Delete SQL Command
dataAdapter.DeleteCommand = connection.CreateCommand();
dataAdapter.DeleteCommand.CommandText =
"DELETE FROM Customers WHERE CustomerID=?";
AddParams(dataAdapter.DeleteCommand, "CustomerID");
}
private void AddParams(OleDbCommand cmd, params string[] cols)
{
foreach (string col in cols)
{
cmd.Parameters.Add(col, OleDbType.Char, 0, col);
}
}
}
}