windows form how to check in database if user already exist? - c#

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

Related

C# program does not connect to a database (freesqldatabase.com)

I'm using freesqldatabase.com to get a database for a college project, so having a remotely accessible database is needed. Unfortunately it does not connect to the database. It connects to their myphpadmin just fine but any other connection fails.
private void Submit_registration(object sender, RoutedEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Data Source= sql2.freesqldatabase.com; Initial Catalog=dbname; User ID=id;Password=no, Integrated Security= True;");
sqlCon.Open();
String query = "INSERT INTO tbluser (ID, username, password) VALUES (#ID, #username, #password)";
String query2 = "SELECT MAX(ID) FROM tbluser";
SqlCommand cmd2 = new SqlCommand(query2, sqlCon);
SqlCommand cmd = new SqlCommand(query, sqlCon);
int maxId = Convert.ToInt32(cmd2.ExecuteScalar());
int newmaxid = maxId + 1;
if (String.Equals(text_password.Password,text_password_confirm.Password))
{
cmd.Parameters.AddWithValue("#ID", newmaxid.ToString());
cmd.Parameters.AddWithValue("#username", textbox_username.Text);
cmd.Parameters.AddWithValue("#password", text_password.Password);
cmd.ExecuteNonQuery();
sqlCon.Close();
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
Close();
}
else
{
MessageBox messageBox = new MessageBox();
messageBox.Show();
sqlCon.Close();
}
}

SQL entries only shown on DataGridSet

I have developed a winforms application with an SQL database in C#. Once I enter the data into the forms and press the display button it is displayed on the datagridview, but once I restart the application the data does not show up on the grid.
This is the code to add new data.
if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
{
con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\shenal.mdf;Integrated Security=True";
cmd = new SqlCommand("insert into [dbo].[user] (Id,username,password) values(#id,#name,#state)", con);
// cmd.CommandText = "insert into [dbo].[user] (Id,username,password) values(#id,#name,#state)";
cmd.Parameters.AddWithValue("#id", textBox1.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text);
cmd.Parameters.AddWithValue("#state", textBox3.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
}
else {
MessageBox.Show("Please Provide Details!");
}
And this is the code to retrieve it.
con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\shenal.mdf;Integrated Security=True";
con.Open();
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("select * from [dbo].[user]", con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();

Why does this UPDATE command not update the data, even though there is no error?

I have a users table having fields uname, ushortname and pswd as well ucode as primary key.
The following UPDATE is not working:
protected void Page_Load(object sender, EventArgs e)
{
string uname = Request.QueryString["uname"];
string ucode = Request.QueryString["ucode"];
if (!string.IsNullOrEmpty(uname))
{
SqlCommand cmd = new SqlCommand("select * from users WHERE ucode=#ucode", conn);
SqlDataAdapter dadapter = new SqlDataAdapter();
conn.Open();
txtUserName.ReadOnly = false;
txtUserShortName.ReadOnly = false;
txtPassword.ReadOnly = false;
dadapter.SelectCommand = cmd;
cmd.Parameters.Add(new SqlParameter("#ucode", ucode));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
LblUcode.Text = dr["ucode"].ToString();
txtPassword.Text=dr["pswd"].ToString();
txtUserShortName.Text = dr["ushortname"].ToString();
txtUserName.Text = dr["uname"].ToString();
}
dr.Close();
conn.Close();
}
}
SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE", conn);
cmd.Parameters.AddWithValue("#Uname", txtUserName.Text);
cmd.Parameters.AddWithValue("#Ushortname", txtUserShortName.Text);
cmd.Parameters.AddWithValue("#Pswd", txtPassword.Text);
cmd.Parameters.AddWithValue("#UCODE", LblUcode.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
There is no error, the data simply isn't being updated.
You need to make sure the parameter names match exactly what they do in your sql string.
cmd.Parameters.AddWithValue("#UCODE", UCODE);
Also, either wrap all of that in a using or try/finally to dispose of the connection. I'm assuming you've already got code to open the connection before trying to execute it.
Try this:-
using(SqlConnection conn = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE ", conn))
{
cmd.Parameters.AddWithValue("#Uname", txtUserName.Text);
cmd.Parameters.AddWithValue("#Ushortname", txtUserShortName.Text);
cmd.Parameters.AddWithValue("#Pswd", txtPassword.Text);
cmd.Parameters.AddWithValue("#UCODE", UCODE);
conn.Open();
cmd.ExecuteNonQuery();
}
}
You are missing # in Ucode. Also, its a good practice to wrap your code inside using block check this.
See the edited below code:-
if (!PostBack)
{
string databaseconnectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
string sql = "update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE";
using (SqlConnection conn = new SqlConnection(databaseconnectionstring))
{
conn.Open();
using (SqlCommand cmd= new SqlCommand())
{
cmd.CommandText=sql;
cmd.Connection=databaseconnectionstring;
cmd.Parameters.AddWithValue("#Uname",txtUserName.Text );
cmd.Parameters.AddWithValue("#Ushortname",txtUserShortName.Text );
cmd.Parameters.AddWithValue("#Pswd",txtPassword.Text );
cmd.Parameters.AddWithValue("#UCODE", UCODE);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
string bsname = Request.QueryString["bsname"];
string bscode = Request.QueryString["bscode"];
if (!string.IsNullOrEmpty(bsname))
{
if (string.IsNullOrEmpty(txtBsName.Text))
{
SqlCommand cmd = new SqlCommand("select * from bs WHERE bscode=#bscode", conn);
SqlDataAdapter dadapter = new SqlDataAdapter();
conn.Open();
txtBsName.ReadOnly = false;
dadapter.SelectCommand = cmd;
cmd.Parameters.Add(new SqlParameter("#bscode", bscode));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lblBsCode.Text = dr["bscode"].ToString();
txtBsName.Text = dr["bsname"].ToString();
}
dr.Close();
conn.Close();
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
conn.Open();
string UCODE = LblUcode.Text;
SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE", conn);
cmd.Parameters.AddWithValue("#Uname",txtUserName.Text );
cmd.Parameters.AddWithValue("#Ushortname",txtUserShortName.Text );
cmd.Parameters.AddWithValue("#Pswd",txtPassword.Text );
cmd.Parameters.AddWithValue("#UCODE", UCODE);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Company Data update Successfully......!");
clear();
}
Thank you all its working now with the help of above code.

Exits don't insert else insert

I have started to learn asp.net. I am using VS 2013 Express for C#.
How to make that a some if case to check a duplicate value and if this value is exists then I get a red summary about it and can't insert to DB else insert to database and too with update button.
Can you help?
SqlConnection con = new SqlConnection(#"Data Source=TSS\SQLEXPRESS;Initial Catalog=DB;Integrated Security=True");
protected void Add(object sender, EventArgs e)
{
var vardas = GridView1.FooterRow.FindControl("txtname") as TextBox;
var pavarde = GridView1.FooterRow.FindControl("txtlastname") as TextBox;
var pozymis = GridView1.FooterRow.FindControl("DropDownList2") as DropDownList;
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into asmenys (name,lastname, status) values(#name,#lastname, #status)";
comm.Connection = con;
comm.Parameters.AddWithValue("#name", name.Text);
comm.Parameters.AddWithValue("#lastname", lastname.Text);
comm.Parameters.AddWithValue("#status", status![enter image description here][1].Text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
DataBind();
}
When you say check if a value exists, what fields should not have duplicates? Those are the fields you have to write a select statement for to check if they exist first.
Example
protected void Add(object sender, EventArgs e)
{
var vardas = GridView1.FooterRow.FindControl("txtname") as TextBox;
var pavarde = GridView1.FooterRow.FindControl("txtlastname") as TextBox;
var pozymis = GridView1.FooterRow.FindControl("DropDownList2") as DropDownList;
SqlCommand comm = new SqlCommand();
comm.CommandText = "select lastname from asmenys where lastname = #lastname";
comm.Parameters.AddWithValue("#lastname", lastname.Text);
SqlDataReader reader = comm.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("Values exist");
}
else
{
comm.CommandText = "insert into asmenys (name,lastname, status) values(#name,#lastname, #status)";
comm.Connection = con;
comm.Parameters.AddWithValue("#name", name.Text);
comm.Parameters.AddWithValue("#lastname", lastname.Text);
comm.Parameters.AddWithValue("#status", status![enter image description here][1].Text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
DataBind();
}
}

Check if Username exists in Database

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.

Categories

Resources