You getting this Error because:
let, your table has two rows:
row1-> checklist_code=code1,order_no=order1,checklist_name=name1
row2->checklist_code=code2,order_no=order2,checklist_name=name2
now, you are trying to search the current table with input(code2,name1),and getting empty result(else part of your condition)
after that, when the code trying to update the table, it's showing the error of violation of Primary key because you are updating the primary key with the value of an existing primary key.[in your else part condition]
i think you got the point where you made a mistake.
protected void checklist_modalpopup_save_Click(object sender, EventArgs e)
{
string c="", d="";
connection();
amicassaCon.Open();
SqlCommand check = new SqlCommand("SELECT checklist_code, order_no FROM checklists Where checklist_name ='" + lblchecklist_popup_name.Text + "' AND checklist_code='" + lblchecklist_popup_code .Text+ "'", amicassaCon);
SqlDataReader rd = check.ExecuteReader();
while (rd.Read())
{
c = rd[0].ToString();
d = rd[1].ToString();
}
rd.Close();
amicassaCon.Close();
if (c == lblchecklist_popup_code.Text || d == lblchecklist_popup_orderno.Text)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Error: Checklist Code/ Order Number have a duplicate in database!');", true);
checklist_popup.Show();
}
else
{
int no=GetNumOfRows_From_checklists("select * from checklists where checklist_code='" + lblchecklist_popup_code .Text+ "'");
if(no==0)
{
connection();
amicassaCon.Open();
SqlCommand cmd = new SqlCommand("UPDATE checklists SET checklist_code='" + lblchecklist_popup_code.Text + "',order_no='" + lblchecklist_popup_orderno.Text + "',checklist_status='" + rrd_checklist_status.SelectedValue + "', checklist_type='" + rrdchecklist_popup_type.SelectedValue + "' WHERE checklist_name = '" + lblchecklist_popup_name.Text + "'", amicassaCon);
SqlDataReader dr = cmd.ExecuteReader();
dr.Close();
amicassaCon.Close();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Error: Updated Checklist Code have a duplicate in table.Try different Checklis Code !');", true);
}
}
connection();
checklist();
}
public int GetNumOfRows_From_checklists(string query)
{
int NumRows=0;
try
{
DataTable dt=new DataTable();
connection();
amicassaCon.Open();
SqlCommand cmd=new SqlCommand(query,amicassaCon);
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt.Rows.Count>0)
{
NumRows=dt.Rows.Count;
}
else
{
NumRows=0;
}
}
catch(exception e1)
{
NumRows=-1;
}
return NumRows;
}