Forum Moderators: open

Message Too Old, No Replies

Preventing database calls on page load

         

skeletor

3:23 pm on May 5, 2008 (gmt 0)

10+ Year Member



So lets say I've got a web page and the C# file looks like this:

public partial class Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Insert(object sender, EventArgs e)
{
string strConn = "my connection string";
string strSQL;

SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;

con = new SqlConnection(strConn);
con.Open();

strSQL = "spInsertMember '" + username.Value + "', '" + password.Value + "', '" + email.Value + "', '" + DateTime.Now + "'";

cmd = new SqlCommand(strSQL, con);
cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

con.Close();

}

The .aspx page has input forms and a submit button that calls the insert function. The problem is that the code in the insert function gets called as soon as the page loads. In fact, no matter where I put the code it will always be executed as soon as the page loads. I've found a couple of ways around this, but I'm curious why this happens. Is there something I'm doing wrong?

bmcgee

11:37 pm on May 6, 2008 (gmt 0)

10+ Year Member



Use IsPostBack() to determine if it is page load, or page reload.