I've written this registration form which adds data to my SQL Server database. What I want is an exception when the user enters a username that is already in the database.
protected void Button1_Click(object sender, EventArgs e)
{
        try
        {
            SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn2.Open();    
            string CheckUser = "select Username from UserData where Username like @Username";
            SqlCommand com2 = new SqlCommand(CheckUser, conn2);        
            com2.Parameters.AddWithValue("@Username", "'%"+ UsernameTextBox.Text +"%'");
            com2.ExecuteNonQuery();
            int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
            conn2.Close();
            if (IsMatch == 0)
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
                conn.Open();
                string InsertQuery = "insert into UserData (Username, Email, Password, Country) values (@Username, @Email, @Password, @Country)";
                SqlCommand com = new SqlCommand(InsertQuery, conn);
                com.Parameters.AddWithValue("@Username", UsernameTextBox.Text);
                com.Parameters.AddWithValue("@Email", EmailTextBox.Text);
                com.Parameters.AddWithValue("@Password", PasswordTextBox.Text);
                com.Parameters.AddWithValue("@Country", CountryDropDownList.SelectedItem.ToString());
                com.ExecuteNonQuery();
                Response.Redirect("Manager.aspx");
                conn.Close();
            }
            else
            {
                Response.Write("User Already Exists!");
            }               
        }
        catch (Exception ex)
        {
            Response.Write(Convert.ToString(ex));
        }
}
When I run it, I get an exception on the following line:
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
 
     
     
     
     
    