How to adjust code to make a sign up form - c#

I am making a project in C# Windows forms. So far I have figured out how to code a login form from YouTube but I don't know how to use the same method to make a sign up form. Here is the code below and I am hoping someone can help make the adjustments so it inserts the username and password into database instead for a user.
try
{
SqlConnection con= new SqlConnection("");
SqlCommand cmd = new SqlCommand("select * from tblLogin where username = #username and password = #password", con);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox2.Text);
SqlDataAdapter da = New SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.fill(dt);
if(dt.Rows.Count>0)
{
MessageBox.Show("login successful");
}
}
catch(Exception ex)
{
MessageBox.Show("" + ex);
}
Incase I have copied the code wrong the link to the video is here: https://youtu.be/nh-fleqcds4

That should be your solution.
You have to insert your textbox values instead of select them.
try
{
SqlConnection con = new SqlConnection("");
SqlCommand cmd = new SqlCommand("insert into tblLogin(username, password)values(#username, #password)", con);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox2.Text);
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("" + ex);
}
This Tutorial is very helpful in my opinion

Related

not getting the correct data

in my log in form I set a username and password and after that I set a query on my Employee_Details then if it successfully log in it will write on another table for history reference so I set a username and Date of log in but it always get the username and password during write in my Employee_History table.Please help me.
private void signin_Click(object sender, EventArgs e)
{
if (IsValidated())
{
try
{
DataTable dt = new DataTable();
String Account_Type;
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\dbms\jollibee.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "select * from Employee_Details where username = #username and password = #password and account_Type";
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#password", password.Text);
OleDbDataReader read = cmd.ExecuteReader();
dt.Load(read);
if(dt.Rows.Count > 0)
{
Account_Type = dt.Rows[0][3].ToString().Trim();
MessageBox.Show("Login Successfull.", "Success", MessageBoxButtons.OK, MessageBoxIcon.None);
if (Account_Type.Equals("Administrator"))
{
admin a = new admin();
a.Show();
this.Hide();
}
else if (Account_Type.Equals("Manager"))
{
supervisor s = new supervisor();
s.Show();
this.Hide();
}
else if (Account_Type.Equals("Cashier"))
{
cashier c = new cashier();
c.Show();
this.Hide();
}
} else
{
MessageBox.Show("Please check your username and password if correct. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
cmd.CommandText = "insert into Employee_History (username, DateLogin) values (?,?);";
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#DateLogin", DateTime.Now.ToString("MM/dd/yyyy HH:mm"));
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message, "Error",MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
}
You are using positional arguments and not clearing the existing arguments. Simply setting a new command text does not "clear" the command, you have to clear it yourself:
cmd.Parameters.Clear(); //<---- ADD THIS LINE
cmd.CommandText = "insert into Employee_History (username, DateLogin) values (?,?);";
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#DateLogin", DateTime.Now.ToString("MM/dd/yyyy HH:mm"));
cmd.ExecuteNonQuery();
I do applaud you for using parameters in your query, I would encourage you to not store passwords in clear text as the next exercise.

double data inserted in sql c#

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 have trouble inserting and deleting rows in my SQL Server database

This is my code for the insert, I got textboxes on my form and I write something inside but when pressing the button with executes the code below it shows an error by the (cmd.ExecuteNonQuery)
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
try
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Heroes (Heroname, Attacktype, patribute, role, role2, role3) VALUES (#Heroname, #Attacktype, #patribute, #role, #role2, #role3)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Heroname", textBox1.Text);
cmd.Parameters.AddWithValue("#Attacktype", textBox2.Text);
cmd.Parameters.AddWithValue("#patribute", textBox3.Text);
cmd.Parameters.AddWithValue("#role", textBox4.Text);
cmd.Parameters.AddWithValue("#role2", textBox5.Text);
cmd.Parameters.AddWithValue("#role3", textBox6.Text);
cmd.ExecuteNonQuery();
textBox1.Clear(); textBox2.Clear();
textBox3.Clear(); textBox4.Clear();
textBox5.Clear(); textBox6.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
The second code snippet is my update code which shows same an error when trying to execute, same error by the execute non query
SqlDataReader reader = null;
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
SqlCommand sda = new SqlCommand("SELECT * FROM Heroes ", cn);
cn.Open();
reader = sda.ExecuteReader();
while (reader.Read())
{
object Heroname = reader["heroname"];
listBox1.Items.Add(Heroname.ToString());
}
reader.Close();
cn.Close();
Please I need help and as quick as someone can, ty!
I think you receive this error, that because you using reserved word Role you should place It in brackets [].
cmd.CommandText = "INSERT INTO Heroes (Heroname, Attacktype,patribute,[role],role2,role3) VALUES (#Heroname, #Attacktype,#patribute,#role,#role2,#role3)";
I suggest to avoid that method of passing parameters, with
cmd.Parameters.AddWithValue("#Heroname", textBox1.Text);
you didn't specify datatype and length, that's correct ADO.NET will guess them but this is not happens always, instead of that try this method:
cmd.Parameters.Add("#Heroname", SqlDbType.VarChar, 50).Value = textBox1.Text;
for all of your parameters.
Was it a null reference exception?
Reading your code, I think you need to change SqlDataReader reader = null; to SqlDataReader reader = new SqlDataReader;
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
try
{
SqlCommand cmd = new SqlCommand("INSERT INTO Heroes (heroname,attacktype,patribute,role,role2,role3) Values (#heroname,#attacktype,#patribute,#role,#role2,#role3) ", cn);
cn.Open();
cmd.Parameters.AddWithValue("#heroname", textBox1.Text);
cmd.Parameters.AddWithValue("#attacktype", textBox2.Text);
cmd.Parameters.AddWithValue("#patribute", textBox3.Text);
cmd.Parameters.AddWithValue("#role", textBox4.Text);
cmd.Parameters.AddWithValue("#role2", textBox5.Text);
cmd.Parameters.AddWithValue("#role3", textBox6.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
This code worked now, inside my form i added a listbox and it does show the added row with its values! But closing form and checking inside database, it doesnt show that row? Whats wrong?

Syntax error in INSERT INTO statement with parameters

i am getting this error so often, i can't find out what's wrong in here?
con.Open();
String query = "INSERT INTO user (username,[password]) values(a,b)";
OleDbCommand cmd1 = new OleDbCommand(query, con);
cmd1.Parameters.AddWithValue("a",textBox1.Text);
cmd1.Parameters.AddWithValue("b", textBox2.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
SqlParameters should start with # like #Name. try this:
con.Open();
String query = "INSERT INTO user (Username, [Password]) values(#Username, #Password)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#Username",textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
Read Using Variables and Parameters

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