Click here to Skip to main content
15,903,175 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LEARNINGConnectionString"].ConnectionString);
            con.Open();
            string checkUser = "select count(*) from login where username='" + TextBox1.Text + "'";
            SqlCommand cod = new SqlCommand(checkUser, con);
            int temp = Convert.ToInt32(cod.ExecuteScalar().ToString());
            con.Close();
            if (temp == 1)
            {
                Response.Write("User already exist");
            }

        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LEARNINGConnectionString"].ConnectionString);
            con.Open();
            string InsertQuery = "insert into login (Username,password) values (@Username,@password)";
            SqlCommand cmd = new SqlCommand(InsertQuery, con);
            cmd.Parameters.AddWithValue("@Username", TextBox1.Text);
            cmd.Parameters.AddWithValue("@password", TextBox2.Text);
            cmd.ExecuteNonQuery();
            Response.Redirect("Admin.aspx");
            Response.Write(" registration sucessfully");
            con.Close();
            
            
            
        }
        catch (Exception ex)
        {
            Response.Write("error" + ex.ToString());

        }
    }
}
Posted
Updated 22-Dec-15 9:47am
v2

1 solution

What errors are you getting? Are there exceptions? Or does the code just not seem to be doing the check in the Page_Load?

I would guess that your check in the Page_Load is working. However, you have no code to stop the Button1_Click event from firing. When you find that the user already exists, you need to stop the Button1_Click event from processing.

One option for this is calling the Response.End() method:
<br />
if (temp == 1)<br />
{<br />
   Response.Write("User already exists");<br />
   Response.End();<br />
}<br />


You could do this by setting some variable (bool _userExists) on the form when the (temp == 1) and then have the Button1_Click event check that value -- if (_userExists) return
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900