The problem seems to be on the id you're passing along to SQL.
Since you created a new record, the id has not changed yet so in your case, you need to set
HiddenField1.Value = ""
before calling 'btn_savprior_Click()' in order to go into that 'if' (Also, I would change the alert as 'Created' instead of 'Saved'):
protected void btn_savprior_Click(object sender, EventArgs e)
{
if (HiddenField1.Value == "")
{
bll.savprior(0, tb_prioname.Text, Convert.ToBoolean(chk_actprior.Checked));
Response.Write("<script>alert('Priority Created Successfully')</script>");
}
I can see that you are setting the value on the first function but, if the value is new, the 'P_ID' column is getting another number (maybe), therefore, the value will never be zero.
Please try to calculate the total and store it on a variable something like:
private int CountRows = 0
Then, you call your DataSet and assign a value to the variable
...
CountRows = GV_PRIOR.Rous.Count;
...
After that, you can modify your function like this:
protected void GV_PRIOR_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
int pid = Convert.ToInt32(GV_PRIOR.DataKeys[e.NewSelectedIndex].Value);
DataTable dt = bll.editprior(pid);
foreach (DataRow dr in dt.Rows)
{
if (Convert.ToInt32(dr["P_ID"].ToString()) > CountRows)
{
HiddenField1.Value = "";
}
else
{
HiddenField1.Value = dr["P_ID"].ToString();
}
tb_prioname.Text = dr["P_NAME"].ToString();
chk_actprior.Checked = dr["P_ACTIVE"].ToString() == "Y";
}
btn_savprior.Text = "UPDATE";
}
Also, if you want to identify right away if will be a new record instead of an update then, this will be the final code for that function:
protected void GV_PRIOR_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
int pid = Convert.ToInt32(GV_PRIOR.DataKeys[e.NewSelectedIndex].Value);
DataTable dt = bll.editprior(pid);
foreach (DataRow dr in dt.Rows)
{
if (Convert.ToInt32(dr["P_ID"].ToString()) > CountRows)
{
HiddenField1.Value = "";
}
else
{
HiddenField1.Value = dr["P_ID"].ToString();
}
tb_prioname.Text = dr["P_NAME"].ToString();
chk_actprior.Checked = dr["P_ACTIVE"].ToString() == "Y";
}
if (HiddenField1.Value == "")
{
btn_savprior.Text = "CREATE";
}
else
{
btn_savprior.Text = "UPDATE";
}
}