The answer was in the Button Click event, after the data has been changed, call DataBind() on the page to cause the GridView (and anything else that needs it) to rebind. I didn't realise you could do that.
Thank you Ocdecio & Mufasa - I would mark your answers as helpful, but I got no rep yet.
that's a common problem. check similar SO questions: Webforms Refresh problem, How to stop unwanted postback.
if a few words, web browser refresh button just sends the last request to the server in your case that's a "Save" button click event
, thus it gives duplicate rows. use Response.Redirect, this way the last request will be just navigation to the page, so the refresh will not cause undesired effects.
EDITED
I see you have added some code. here's a workaround for you. the fact that you are saving data to database helps a lot. first thing on page load event no need to check if page IsPostBack, just call the bindassets("", "");
method.
as for save button click event. no need to call the bindassets("", "");
it will be called from page load.
protected void btnsaveasset_Click(object sender, EventArgs e)
{
if (txtdescription.Text != "" && txtdtrecieved.Text != "" && txtcost.Text != "" && txtmodelno.Text != "" && txtquantity.Text != "")
{
try
{
string desc= txtdescription.Text;
DateTime dtrecd = Convert.ToDateTime(txtdtrecieved.Text);
string cost = txtcost.Text;
string modelno = txtmodelno.Text;
double quantity = Convert.ToDouble(txtquantity.Text);
SqlConnection sqlcon = new SqlConnection(con);
sqlcon.Open();
string save = "Insert into Asset(Description,Recieveddate,cost,Modelno,Quantity)values(@desc,@date,@cost,@modelno,@quantity)";
SqlCommand cmd = new SqlCommand(save, sqlcon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@desc", desc);
cmd.Parameters.Add("@date", dtrecd);
cmd.Parameters.Add("@cost", cost);
cmd.Parameters.Add("@modelno", modelno);
cmd.Parameters.Add("@quantity", quantity);
cmd.ExecuteNonQuery();
sqlcon.Close();
//bindassets("", "");
btnsaveasset.Enabled = false;
txtdescription.Text = "";
txtdtrecieved.Text = "";
txtcost.Text = "";
txtmodelno.Text = "";
txtquantity.Text = "";
lblErrMsg.Text = "data inserted successfully..";
}
catch
{
lblErrMsg.Text = "Please enter valid data and try again...";
}
}
else
{
lblErrMsg.Text = "Please enter valid data and try again...";
}
Response.Redirect("nameofpage.aspx", false);//does a charm. browser refresh button will repeat last action and from now on that's a Response.Redirect("nameofpage.aspx", false). thus no duplicate records
}
Best Answer
The GridView.DataBind Method will clear and re-populate your grid view (assuming the datasource is already set - see the link for an example).