I have a problem with insert command in C# WinForm. I need to insert special char so I need parameter or some alternative. But I can't insert the data into db. My 2nd column RecordNo allows unique and is a integer. This is where I'm facing trouble. After saving one rec when I change the RecordNo and try to save data it is showing data is duplicate. Plzz help me fix my problem.
My Code:
private void saverec_Click(object sender, EventArgs e)
{
try
{
int recva = Convert.ToInt32(recno_tb.Text);
myconn.ConnectionString = connestr;
dtcmd.CommandText = "INSERT INTO FormEntry (RecordNo) values ("+ recva + ")";
dtcmd.Connection = myconn;
myconn.Open();
dtcmd.ExecuteNonQuery();
myconn.Close();
dataconnect();
myconn.ConnectionString = connestr;
dtcmd.CommandText = "UPDATE FormEntry SET ImageName = @imagena,EmailId = @email WHERE [RecordNo] = " + recva + ""; dtcmd.Parameters.Add("@imagena", OleDbType.VarChar).Value = imgname_tb.Text;
//dtcmd.Parameters.AddWithValue("@recno", recno_tb.Text);
dtcmd.Parameters.AddWithValue("@email", OleDbType.VarChar).Value = email_tb.Text;
dtcmd.Connection = myconn;
myconn.Open();
dtcmd.ExecuteNonQuery();
myconn.Close();
dataconnect();
addnew_Click(sender, e);
recno_tb.Text = (recva + 1).ToString();
email_tb.Focus();
}
catch (Exception ex)
{
if (ex.Message.ToString() == "The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.")
{
MessageBox.Show("Record already exists. Try entering new record.\nYou can also find and edit the record.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (ex.Message.ToString() == "Field 'FormEntry.RecordNo' cannot be a zero-length string.")
{
MessageBox.Show("Record No can't be null", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
myconn.Close();
}
I had googled it but no use. So plz help me.