2

while inserting record in sql server database. every time inserting 2 records, i think event firing two times. how to stop inserting records twice in ado.net.

protected void btnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        CompanyName = txtCompany.Text.Trim();
        InsertData();
    }
    catch (Exception)
    {
        throw;
    }
}

private void InsertData()
{
    if (Page.IsPostBack)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["kernelCS"].ConnectionString);
        SqlCommand cmd = new SqlCommand(@"INSERT INTO [tbl_Leads]([CompanyName])VALUES(@CompanyName)", con);
        cmd.Parameters.AddWithValue("@CompanyName", txtCompany.Text.ToString());
        con.Open();
        cmd.ExecuteNonQuery();
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        ...
    }
}
3
  • Why you have if (Page.IsPostBack) in your private method? Commented Dec 14, 2015 at 6:21
  • can you post your asp client side code? Commented Dec 14, 2015 at 6:22
  • i tried to stop inserting twice .so i used page.ispostback@RahulSingh Commented Dec 14, 2015 at 6:23

2 Answers 2

6

You are firing the query twice in your code by cmd.ExecuteNonQuery() and da.Fill(ds) statements.

Sign up to request clarification or add additional context in comments.

Comments

0

Try This :

private void InsertData()
{
  SqlConnection con = new  SqlConnection(ConfigurationManager.
  ConnectionStrings["kernelCS"].ConnectionString);
  SqlCommand cmd = new SqlCommand(@"INSERT INTO [tbl_Leads]
  ([CompanyName]) VALUES (@CompanyName)", con);
  cmd.Parameters.AddWithValue("@CompanyName", txtCompany.Text.ToString());

  con.Open();
  cmd.ExecuteNonQuery();
}`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.