Insert and Update Function work on single button click in c# - c#

I am trying to insert and update data using same button. I have created method(uniqueEmail()) to check the email address exist in table or not. Using this method I am trying to insert data if email is not preset.
here is my code please correct me where I am going wrong.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}

You need to check for the count of the particular emailId, not the total count.
Modify the code as below:
public static bool uniqueEmail(string email)
{
string stremail;
string querye = "select count(email) as email from register where
email = '" + email + "'";
//Remaining Code
}
public static void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail(TextBox1.Text)) == true)
//Remaining Code
}

#nirmala you should replace method
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= #EmailId", con);
cmd.Parameters.AddWithValue("#EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}

Two Things need to be done
Pass the Email Id while calling
if (uniqueEmail()==true)
To
if (uniqueEmail(TextBox1.Text)==true)
And in uniqueEmail method chenage the query ()include where condition as below
public bool uniqueEmail(email)
{
string stremail;
string querye = "select count(email) as email from registeruser where email='" + email + "'";
//your remaining code
}

Hi Nirmala your code is correct only you need to put where clause to find the email id already exist in the Database.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser where email = '" +TextBox1.Text+ "'";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}

Related

Connection is not closed properly ASP.NET C#

I have this button click event. Been trying to replace the con.Close() in different lines of code, tried for hours but couldn't fix. Maybe a second pair of eyes can help?
Error: System.InvalidOperationException: 'The connection was not closed. The connection's current state is open.'
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
con.Open();
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
con.Close();
}
else
{
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
con.Open();
int i = cmd1.ExecuteNonQuery();
con.Close();
if (i != 0)
{
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
}
else
{
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
}
Try this (open connection only once and close only once):
protected void Button1_Click(object sender, EventArgs e) {
using(SqlConnection con = new SqlConnection()) {
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
bool hasRows = reader.HasRows;
reader.Close();
if (hasRows) {
// This line makes no sense after the execution of the query.
//cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
} else {
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
int i = cmd1.ExecuteNonQuery();
if (i != 0) {
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
} else {
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
con.Close();
}
}
Now let's discuss this line
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
This let's attacker manipulate your input with sql injection. To solve this, use the same cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value); that you are using in the second query. The Session["id"] is somewhat safer as it is not provided by the user but better safe than sorry as the parameters sanitize the input and protect you from sql injection.

Username check is not working when user registers -asp.net

i want to check if the username already exists in the database and if yes, error message will prompt that says "username already exist". now i have this code but its not working. program still accepts the username even if it is duplicated from the database. can someone help me out pls? here is my whole registration code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
if (temp == 1) // check if user already exist.
{
Response.Write("User already existing");
}
conn.Close();
}
}
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
SqlCommand scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
You validate data on Page_Load? I think, you can choose to these solusions
You have to do it in btn_Registration_Click before you insert the
data, or
Maybe, you can modify it to do in sp and throw message through it if data is
duplicated and do the checking there.
It should be like this (according to solution 1)
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
if (temp > 0) // check if user already exist.
{
Response.Write("User already existing");
}
else
{
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
}
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}

Object reference not set to an instance of an object for asp.net

protected void Page_Load(object sender, EventArgs e)
{
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ProfileCS"].ConnectionString;
string sql = "Select password from Profile where userid = '" + Session["userid"] + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr; // to hold reference of datareader returned
//prepare a place - datatable to hold the data
DataTable dt = new DataTable();
//setting up command
cmd.CommandText = sql;
cmd.Connection = con;
//connection and execute command
con.Open();
dr = cmd.ExecuteReader();
dt.Load(dr); // copy data from datareader to datatable
string pwdcheck;
pwdcheck = dt.Rows[0]["password"].ToString();
if (tb_verify.Text.Equals(pwdcheck))
{
string password = tb_pwd.Text;
sql = "Update Profile set password ='" + password + "'";
sql = sql + "where userid = '" + Session["userid"] + "'";
cmd.CommandText = sql;
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
lb_msg.Text = "Password changed succesfully";
}
catch (Exception ex)
{
lb_msg.Text = "Problems encountered " + ex.Message;
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}
}
else
lb_msg.Text = "Old password Incorrect";
}
protected void lblClick(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Session.Clear(); // This may not be needed -- but can't hurt
Session.Abandon();
FormsAuthentication.RedirectToLoginPage();
}
}
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
there is an error at the line above with
Object reference not set to an instance of an object the change password feature was working before.
In your case Session["userid"] must be NULL,handle it

How to get next data row by hiting on Next button

I want to get next record from table to show as Question. With below code I am not able to get next Question from table.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
Quiz_Load();
}
}
private void Quiz_Load()
{
try
{
if (Session["UserQuizID"] != null)
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("select top 0.1 percent QuestionID, Title, Answer1,Answer2,Answer3,Answer4,UserAnswer from [Table_UserAnswer] WHERE UserQuizID = '" + UserQuiz_ID.ToString() + "' AND UserName = '" + mayank.ToString() + "' order by newid()", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["QuestionID"] = dr[0].ToString();
Lbl_QuestionTitle.Text = dr[1].ToString();
RadBut_Answer.Items.Add(dr[2].ToString());
RadBut_Answer.Items.Add(dr[3].ToString());
RadBut_Answer.Items.Add(dr[4].ToString());
RadBut_Answer.Items.Add(dr[5].ToString());
Session["UserAnswer"] = dr[6].ToString();
}
else
{
}
con.Close();
}
else
{
Response.Redirect("Start.aspx");
}
}
catch
{
}
}
protected void RadBut_Answer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int getvalue;
getvalue = Convert.ToInt32(RadBut_Answer.SelectedIndex + 1);
Lbl_SelectedAnsMsg.Text = MessageFormatter.GetFormattedAlertsMessage("Your Selected Answer is : " + getvalue.ToString());
Session["UserAnswer"] = getvalue.ToString();
}
catch
{
}
}
protected void But_Next_Click(object sender, EventArgs e)
{
UpdateUserAns();
if (Session["UserAnswer"] == null)
{
Response.Redirect("Result.aspx");
}
else
{
}
}
private void UpdateUserAns()
{
try
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
string Question_ID = Session["QuestionID"].ToString();
string User_Answer = Session["UserAnswer"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("UPDATE Table_UserAnswer SET UserAnswer='" + User_Answer.ToString() + "' WHERE UserQuizID = '"+ UserQuiz_ID.ToString() +"' AND QuestionID = '"+Question_ID.ToString()+"' AND UserName = '"+mayank.ToString()+"'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Cancel();
}
catch
{
}
}
hi check this post client here
here you can find solution of your question

update not working

protected void Page_Load(object sender, EventArgs e)
{
txtHidden.Text = Request.QueryString["YKcode"];
Display();
}
private void Display()
{
SqlDataReader reader;
SqlConnection con = new SqlConnection("Data Source=Localhost;Initial Catalog=MLC000022;User ID=sa;Password=Adama6DaY; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT " + " dbo.GMYAKU.NAME, " +"FROM " +
" dbo.GMYAKU " + " WHERE " +
" (dbo.GMYAKU.YKCODE = ('" + txtHidden.Text + "'))",con) ;
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
this.TextBox1.Text = reader["NAME"].ToString();
}
else
{
// 読めないので画面を初期化する
}
cmd.Connection.Close();
cmd.Dispose();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
SqlCommand cmd;
connetionString = ("Data Source=Localhost;Initial Catalog=MLC000022;User ID=sa;Password=redacted; Integrated Security=True");
string strSQL ;
strSQL = "UPDATE GMYAKU SET";
strSQL += " NAME = '" + (TextBox1.Text) + "'";
strSQL += " WHERE";
strSQL += " YKCODE= '" + txtHidden.Text + "'";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(strSQL, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
// cnn.Close();
//MessageBox.Show(" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
// MessageBox.Show("Can not open connection ! ");
}
Response.Redirect("Default.aspx");
}
It may be something as simple as not having the control in an update panel to refresh with the new data, but without more information/context it is impossible to tell
I think you need to check the Request.QueryString["YKcode"]; before assigning value to txthidden.text like:
protected void Page_Load(object sender, EventArgs e)
{
if(!Request.QueryString["YKcode"].equals("") && Request.QueryString["YKcode"]!=null)
{
txtHidden.Text = Request.QueryString["YKcode"];
Display();
}
}

Categories