Reputation: 587
I am struggling for updating record/columnvalue in MS-ACCESS database... help would be appreciated a lot..!
I am displaying a list of partnumbers retrieved from a table in Ms-access using Datagridview in which I am supposed to update/change partnumber. ( 'partno' is 3rd column of my datagridview.)
But I am unable to Update a single record in database..no exceptions.. everything is going fine.!
But no rows are effected!
Here is my code:
private void UpdateDetails_Click(object sender, EventArgs e)
{
try
{
con = new OleDbConnection();
con.ConnectionString = Helper.MyConnectionString;
con.Open();
for (int i = 0; i <= datagridview1.Rows.Count-1; i++)
{
int j = i + 1; // j is the serial number corresponding to partnumber
string partno = dgv1.Rows[i].Cells[2].Value.ToString(); //getting part number from Datagridview
String partquery = "";
if (partno == null || partno == "") //checking whether part number updated or not
{
partquery = "update Vendor SET PartNo=NULL where Vendor.Sno=" + j + " ";
}
else
partquery = "update Vendor SET PartNo='" + partno + "' where Vendor.Sno=" + j + " ";
//Vendor is the table name containg 'partno' list
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = partquery;
cmd.ExecuteNonQuery();
}
}
catch(Exception ex)
{
//exception handler
}
}
Upvotes: 0
Views: 2274
Reputation: 2691
As @Soner suggested you should use parameters. Something like this.
Modified the code did you do something like this?
private void UpdateDetails_Click(object sender, EventArgs e)
{
try
{
con = new OleDbConnection();
con.ConnectionString = Helper.MyConnectionString;
con.Open();
for (int i = 0; i <= datagridview1.Rows.Count - 1; i++)
{
int j = i + 1; // j is the serial number corresponding to partnumber
string partno = dgv1.Rows[i].Cells[2].Value.ToString(); //getting part number from Datagridview
//String partquery = "";
//if (partno == null || partno == "") //checking whether part number updated or not
//{
// partquery = "update Vendor SET PartNo=NULL where Vendor.Sno=" + j + " ";
//}
//else
// partquery = "update Vendor SET PartNo='" + partno + "' where Vendor.Sno=" + j + " ";
OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("update Vendor SET PartNo='@partno' where Vendor.Sno=@vndid");
OleDbParameter parameter = new System.Data.OleDb.OleDbParameter("@partno", partno);
cmd.Parameters.Add(parameter);
parameter = new System.Data.OleDb.OleDbParameter("@vndid", j);
cmd.Parameters.Add(parameter);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//exception handler
}
}
Upvotes: 1