"Insert into Table" statement- Values Repeating. Need help

Posted by Sina under Sql Server on 2/28/2011 | Points: 10 | Views : 1547 | Status : [Member] | Replies : 3
Hi i need immediate help in solving Sql query issue. After i debug my code and view data in the corresponding database table i see the value appears twice. Please help me to solve my issue immediately Below is my code in C#:

protected void Page_Load(object sender, EventArgs e)
{
string connectionstring= "Data Source=.\\SQLEXPRESS;AttachDbFilename= C:\\Documents and Settings\\escube\\My Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True";
SqlConnection con= new SqlConnection (connectionstring);
con.Open ();
string query = "insert into TblData values('Prasidh',1)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}

@Sina


Responses

Posted by: Krkc on: 3/1/2011 [Member] Starter | Points: 25

Up
0
Down
Hi, you have written your code Page_Load event which fires when ever there is a Postback happens.

1. Try placing your code in some Button_Click event.
OR
2. Keep the condition If(!IsPostBack) before executing your database query.



Thanks,
Ravi

Sina, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: T.saravanan on: 3/1/2011 [Member] [MVP] Silver | Points: 25

Up
0
Down
Hi,

Are you using any other controls like button,DropDownlist in your page.
if yes means check IsPostBack condition in your page load event...

protected void Page_Load(object sender, EventArgs e)

{
if(!IsPostBack)
{

string connectionstring= "Data Source=.\\SQLEXPRESS;AttachDbFilename= C:\\Documents and Settings\\escube\\My Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True";
SqlConnection con= new SqlConnection (connectionstring);
con.Open ();
string query = "insert into TblData values('Prasidh',1)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
}


Try this.....

Cheers :)


Thanks,
T.Saravanan

Sina, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sina on: 3/1/2011 [Member] Starter | Points: 25

Up
0
Down
Thanks to both of u for the quick response...It worked!!

@Sina

Sina, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response