I am trying to code a register application form. In the code below I want to check if the username exists before i save the data in Database.
The problem here that the code doesn't go to the "else" statement.
Do I miss something? Kindly help
public void UserNameCheck()
{
string connetionString = null;
SqlConnection con;
connetionString = "Data Source=MCOEELIMENEM\\sqlexpress;Initial Catalog=Database;Integrated Security=True";
con = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand("Select * from Register where Username= #Username", con);
cmd.Parameters.AddWithValue("#Username", this.textBox1.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Username = " + dr[1].ToString() + " Already exist");
break;
}
else
{
cmd.CommandText = "insert into Register(Username,Password,Fullname,MobileNO,EmailID) values( #Username, #Password, #Fullname, #MobileNO, #EmailID)";
cmd.Parameters.AddWithValue("#Username", textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Fullname", textBox3.Text);
cmd.Parameters.AddWithValue("#MobileNO", textBox4.Text);
cmd.Parameters.AddWithValue("#EmailID", textBox5.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted Succesfully");
con.Close();
this.Hide();
Login lg = new Login();
lg.Show();
}
}
}
The query will not return any rows (therefore the Read() statement will fail) where the user exists.
Try this (untested):
SqlCommand cmd = new SqlCommand("Select count(*) from Register where Username= #Username", con);
cmd.Parameters.AddWithValue("#Username", this.textBox1.Text);
con.Open();
var result = cmd.ExecuteScalar();
if (result != null)
{
MessageBox.Show(string.format("Username {0} already exist", this.textBox1.Text));
}
else
{
...
If dr.Read() returns true, then your reader always has rows.
EDIT:
As long, as you do not getting any values from DB, you can remove while(dr.Read()) statement, and your code will work as you need
I recommand you to not select all columns, instead just select id and check with ExecuteScalar method of SqlCommand, that would be optimum solution.
SqlCommand cmd = new SqlCommand("Select id from Register where Username= #Username", con);
cmd.Parameters.AddWithValue("#Username", this.textBox1.Text);
con.Open();
var nId = cmd.ExecuteScalar();
if(nId != null)
{
// Prompt user is already exists
}
else
{
// Insert record
}
You must check with the number of rows returned by the query.
Related
This is just a simple way of registering new account credentials. My problem is that whenever I click the save button, the data will be saved twice in the database.
Sample image of the double entry in the database.
using (SqlConnection con = new SqlConnection(conString))
{
try
{
string query = ("INSERT INTO Tbl_Staff (Name,pos,username,password) VALUES (#name,#pos,#username,#password)");
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#name", textBox1.Text);
cmd.Parameters.AddWithValue("#pos", textBox4.Text);
cmd.Parameters.AddWithValue("#username", textBox2.Text);
cmd.Parameters.AddWithValue("#password", textBox3.Text);
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
//MessageBox.Show(result.ToString());
// Check Error
if (result > 0)
MessageBox.Show("Credentials has been successfully added.","" ,MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You're calling ExecuteNonQuery() twice.
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
you excecute the query twice.
change:
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
to
con.Open();
int result = cmd.ExecuteNonQuery();
I am unable to send lasted inserted autoincrement id value to another table
this is my code
i am getting error is Must declare the scalar variable "#userid".
int ID;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()", cn);
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
cmd.ExecuteNonQuery();
ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
SqlCommand cmd2 = new SqlCommand("insert into sampfk values(#emailid,#address,#userid)", cn);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text);
cmd2.Parameters.AddWithValue("#userid", ID);
cn.Open();
cmd2.ExecuteNonQuery();
cn.Close();
cmd.Dispose();
TextBox3.Text = "";
TextBox4.Text = "";
I think I got your problem.you have written
SqlCommand cmd2 = new SqlCommand("insert into sampfk values (#userid, #address, #emailid)", cn);
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text)
but executing
cmd2.ExecuteNonQuery();
you should add parameter in cmd2 not cmd like as
cmd2.Parameters.AddWithValue("#userid", ID);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text)
You can do above in single step, you should use using more and try to nest query if possible. Opening TCP connection frequently has some acknowledgement overheads.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString))
{
string query = #"INSERT INTO sampdb VALUES (#name,#phone);
INSERT INTO sampfk VALUES (SCOPE_IDENITTY(), #address, #emailid); ";
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
Check the following line.
ID = Convert.ToInt32(cmd.ExecuteScalar());
If this doesn't return anything, then use a default value for ID, maybe 0.
Or add a default value in the declaration as int id = 0;
try this
using (SqlConnection cn = new SqlConnection(connectionStr))
{
string sql1 = "insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()";
using (SqlCommand cmd = new SqlCommand(sql1, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
ID = cmd.ExecuteNonQuery();
}
//ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
string sql2 = "insert into sampfk values (#userid, #address, #emailid)";
using (SqlCommand cmd = new SqlCommand(sql2, cn))
{
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
con.Dispose();
con.Close();
}
this is the code i have used to validate both username and password from the database. but it always navigates to the first if condition. But is HR group has the same password and SW dev group has the same password. i need to validate the password and need to navigate to the Form.
private void button1_Click(object sender, EventArgs e)
{
con.Open();
string usrnm = txtusrnm.Text;
string pass = txtpass.Text;
SqlDataReader reader = null;
string qry = "select username, password from login where username=#username and password=#password";
//SqlCommand cmd = new SqlCommand();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#username", txtusrnm.Text);
cmd.Parameters.AddWithValue("#password", txtpass.Text);
reader = cmd.ExecuteReader();
if (reader != null ||reader.HasRows)
{
//if username is matching
MessageBox.Show("Redirecting to HR..");
frm_hr fhr = new frm_hr();
fhr.Show();
this.Hide();
}
else
{
//if not matching do something
MessageBox.Show("Redirecting to Software Developer..");
frm_swdev fsw = new frm_swdev();
fsw.Show();
this.Hide();
}
con.Close();
}
in your code there is this :
reader = cmd.ExecuteReader();
if (reader != null ||reader.HasRows)
this will always be true, because reader will always != null
change it to
reader = cmd.ExecuteReader();
if (reader.HasRows)
An alternate idea to reader.HasRows - change your query to count the number of rows that contain the username/password, then you will always return a value of 0 or 1...
string qry = "select count(*) from login where username=#username and password=#password";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#username", txtusrnm.Text);
cmd.Parameters.AddWithValue("#password", txtpass.Text);
int iValue = (int)cmd.ExecuteScalar();
I want to create a simple form where I want to validate to show message if same users exists.
The function usernamecheck() checks for validation and displays error if same user exists but when I click submit button it still submits same user.
private void submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(#fname,#lname,#alias,#contact,#address,#company,#bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#fname", textBox1.Text);
cmd.Parameters.AddWithValue("#lname", textBox2.Text);
cmd.Parameters.AddWithValue("#alias", textBox3.Text);
cmd.Parameters.AddWithValue("#contact", textBox4.Text);
cmd.Parameters.AddWithValue("#address", textBox5.Text);
cmd.Parameters.AddWithValue("#company", textBox6.Text);
cmd.Parameters.AddWithValue("#bdate", textBox7.Text.ToString());
UserNameCheck();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted Succesfully");
}
public void UserNameCheck()
{
string constring = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from cntc_employee where emp_alias= #alias", con);
cmd.Parameters.AddWithValue("#alias", this.textBox3.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Alias "+ dr[1].ToString() +" Already exist");
break;
}
}
}
Problem : You are Inserting the record always without check wether user exist or not.
Solution :
You need to return the boolean value from the UserNameCheck() function.
retrun true if username exist.
return false if username doesnot exist.
then execute the Insert Query if and only if UserNameCheck function returns false
Try This:
Chnage the UserNameCheck() function code as below to return the boolean value.
public bool UserNameCheck()
{
string constring = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select count(*) from cntc_employee where emp_alias= #alias", con);
cmd.Parameters.AddWithValue("#alias", this.textBox3.Text);
con.Open();
int TotalRows = 0;
TotalRows = Convert.ToInt32(cmd.ExecuteScalar());
if(TotalRows > 0)
{
MessageBox.Show("Alias "+ dr[1].ToString() +" Already exist");
return true;
}
else
{
return false;
}
}
Now Change the Submit function code to verify the UserNameCheck() return value, proceed to the insertion only if the UserNameCheck() function returns false(when user does not exist)
private void submit_Click(object sender, EventArgs e)
{
if(!UserNameCheck())
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(#fname,#lname,#alias,#contact,#address,#company,#bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#fname", textBox1.Text);
cmd.Parameters.AddWithValue("#lname", textBox2.Text);
cmd.Parameters.AddWithValue("#alias", textBox3.Text);
cmd.Parameters.AddWithValue("#contact", textBox4.Text);
cmd.Parameters.AddWithValue("#address", textBox5.Text);
cmd.Parameters.AddWithValue("#company", textBox6.Text);
cmd.Parameters.AddWithValue("#bdate", textBox7.Text.ToString());
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted Succesfully");
}
}
First fire a select query that checks whether a user exists or not. If not then fire insert statement.
you should make a select count by name for the user first, and if the counter is bigger than 0 make the insert
Actually my code was suppose to check that is there any value in the course_choice_teacher table. If there is not, then it will insert some values into the table. Now this time there is no value in the table. So dr2.Read() should return false and do the else portion. But it is doing the reverse thing. I'll be very happy if you help me in this purpose.
string oradb = "Data Source=localhost;User Id=system;Password=cse;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd2 = new OracleCommand();
cmd2.Connection = conn;
cmd2.CommandText = "select * from course_choice_teacher where teacher_id='"+teacher_home.st+"' and choice_no=1";
cmd2.CommandType = CommandType.Text;
OracleDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
MessageBox.Show("Already Given");
}
else
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into course_choice_teacher values('" + teacher_home.st + "','" + dataGridView1.CurrentRow.Cells["course_id"].Value.ToString() + "',1)";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
}
conn.Dispose();
The datareader has property .HasRows to check if the result has some rows. This would be a proper way to check what you intend to do.
if (dr2.HasRows)
{
MessageBox.Show("Already Given");
}
else
{
.........
}