I'm trying to create simple log in page with visual studio win form. I have got username and password as textbox controls.
here is the event which should check if there is such kind of user in database:
if (con.State != ConnectionState.Open)
{
con.Open();
}
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = "select staff_username, staff_password from staff_accounts";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if (username.Text == dr["staff_username"].ToString() && pass.Text == dr["staff_password"].ToString())
{
admin.ShowDialog();
}
else
{
label1.Text = "Error";
}
}
}
dr.HasRows returns false, so it means that cmd.CommandText = "select staff_username, staff_password from staff_accounts"; returns no rows, but in my database the same query works fine.
any kind of help will be appreciated.
You should check HasRows property before calling reader Read() method. Try:
if (dr.HasRows)
{
while (dr.Read())
{
....
Related
I have a DropDownList that gets populated by a SQL Server table called tblVisa. My issue is that the values that are being populated from the SQL Server table are not being saved. Everything else gets saved except for my DropDownLists. I've tried using .SelectedValue and .Text, but it still does not work.
Here is my code
protected void PopulateVisaType()
{
List<ListItem> result = new List<ListItem> { new ListItem("", "") };
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "SELECT VisaType FROM tblVisa ORDER BY VisaType ASC" };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
result.Add(new ListItem(read["VisaType"].ToString(), read["VisaType"].ToString()));
}
read.Close();
sqlConn.Close();
cmd.Dispose();
DDLVisa.DataSource = result;
DDLVisa.DataValueField = "value";
DDLVisa.DataTextField = "text";
DDLVisa.DataBind();
}
Here's my code for saving the information into the database:
protected void LbSaveProfile_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "spSaveNewProviderInformation", CommandType = CommandType.StoredProcedure };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
cmd.Parameters.AddWithValue("#EmployeeNumber", TbEmployeeNumber.Text.Trim());
cmd.Parameters.AddWithValue("#SSN", TbSSN.Text.Trim());
cmd.Parameters.AddWithValue("#ContractType", DDLContractType.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Firstname", TbFirstname.Text.Trim());
cmd.Parameters.AddWithValue("#Lastname", TbLastname.Text.Trim());
cmd.Parameters.AddWithValue("#MiddleInitial", TbMiddleInitial.Text.Trim());
cmd.Parameters.AddWithValue("#ContractRenewalDate", TbContractRenewalDate.Text.Trim());
cmd.Parameters.AddWithValue("#Position", DDLPosition.Text.Trim());
cmd.Parameters.AddWithValue("#Specialty", DDLSpecialty.Text.Trim());
cmd.Parameters.AddWithValue("#PrimaryDepartment", DDLPrimaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#SecondaryDepartment", DDLSecondaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#Gender", DDLGender.Text.Trim());
cmd.Parameters.AddWithValue("#Birthdate", TbBirthdate.Text.Trim());
cmd.Parameters.AddWithValue("#EmailAddress", TbEmailAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PhoneNumber", TbPhoneNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Address", TbAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PassportNumber", TbPassportNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Citizenship", DDLCitizenship.Text.Trim());
cmd.Parameters.AddWithValue("#Visa", DDLVisa.Text.Trim());
cmd.Parameters.AddWithValue("#Status", 1);
cmd.ExecuteNonQuery();
sqlConn.Close();
Alert("Provider Information saved!");
ClearControls();
}
You much better to provide the drop down list with column names.
So, say this:
protected void PopulateVisaType()
{
SqlConnection sqlConn = new SqlConnection("");
using (SqlCommand cmd = new SqlCommand("SELECT VisaType FROM tblVisa ORDER BY VisaType ASC", sqlConn))
{
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
DDLVisa.DataSource = cmd.ExecuteReader();
DDLVisa.DataValueField = "VisaType";
DDLVisa.DataTextField = "VisaType";
DDLVisa.DataBind();
//DDLVisa.Items.Insert(0, new ListItem("")); // optional blank row choice
sqlConn.Close();
}
}
So the TextField, and the DataText field need to be a named column from the data source.
I also included an optional first blank option if you need/want/expect to have no choice.
However, keep in mind that this empty string should be translated into a null in your database if you don't allow (or want) empty strings, and want a null for that value. This applies to all of your values. (perhaps the stored procedure does this?).
I am trying to make a login at the moment. I watched some videos and found a good way. Every user has an id, Username and Password. I want to get the id of the user who has just been logged in and save it in an Integer. I also tried it with an ExecuteReader but I get an Exception(MySql.Data.MySqlClient.MySqlException).
My current Code is:
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
string query = "SELECT COUNT(1) FROM Users_Table WHERE Username=#Username AND Password=#Password;";
MySqlCommand sqlCmd = new MySqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username", maintxtbox1.Text);
sqlCmd.Parameters.AddWithValue("#Password", Hashed_Password);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
//Login correct
}
else
{
//Login incorrect
}
}
catch
{
//Exception
}
finally
{
sqlCon.Close();
}
The try with the ExecuteReader:
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
string query = "SELECT id,Username,Password FROM Users_Table WHERE Username=#Username AND Password=#Password;";
MySqlCommand sqlCmd = new MySqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username", maintxtbox1.Text);
sqlCmd.Parameters.AddWithValue("#Password", Hashed_Password);
MySqlDataReader datareader = sqlCmd.ExecuteReader();
if (datareader.HasRows)
{
MessageBox.Show("Test: " + datareader.GetString("id"));
}
else
{
//Login incorrect
}
}
catch
{
//Exception
}
finally
{
sqlCon.Close();
}
I hope somebody can help me. Thank you in advance.
Try and use the Read method:
if(datareader.Read()){
MessageBox.Show("Test: "+datareader.GetString(0));
}
EDIT:
To make good use and disposal of resources I recommend using the MySqlDataReader inside a using block, e.j.
using(MySqlDataReader reader = new sqlCmd.ExecuteReader()){
if(reader.Read()){
MessageBox.Show("Test: "+reader.GetString(0));
}
}
I found a solution to my Question by myself. I forgot the while(datareader.Read()) in the ìf(datareader.HasRows) query. Here is my working Code:
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
string query = "SELECT * FROM Users_Table WHERE username=#Username AND password=#Password;";
MySqlCommand sqlCmd = new MySqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username", maintxtbox1.Text);
sqlCmd.Parameters.AddWithValue("#Password", Hashed_Password);
MySqlDataReader datareader = sqlCmd.ExecuteReader();
if (datareader.HasRows)
{
while (datareader.Read())
{
UserID = datareader.GetInt32("id");
}
}
else
{
//Incorrect Password
}
}
catch
{
//Error
}
finally
{
sqlCon.Close();
}
I want to store values of SqlCommand in string variable and print it on label. Here is my C# code
String sq="select fullname,emailId from Registration where RgId= '"+Session["RgId"]+"'";
SqlCommand cmd1 = new SqlCommand(sq, con);
con.Open();
SqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
while(rdr.Read())
{
string fname = (string)rdr["fullname"];
string femail=(string)rdr["emailId"];
Label4.Text = fname;
label5.Text=femail;
}
if(rdr!= null)
{
rdr.Close();
}
con.Close();
but instead of printing value it doesn't show value on label. What to do? Is there anything wrong in code?
I would recommend using using statements when dealing with db access. Things get cleaned up better this way. Since your not using a try/catch in the code provided I would assume your using it in an outer layer or something so I would:
if (Session["RgId"] == null)
throw new NullReferenceException("RgId");
using (var con = new SqlConnection())
{
const string sql = "select fullname,emailId from Registration where RgId = #RgId";
using (var cmd1 = new SqlCommand(sql, con))
{
cmd1.Parameters.Add(new SqlParameter("RdId", SqlDbType.Int) {Value = Session["RgId"]});
con.Open();
using (var rdr = cmd1.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
Label4.Text = (string) rdr["fullname"];
label5.Text = (string) rdr["emailId"];
}
else
{
//handle registration not found
}
rdr.Close();
}
}
}
To make SQL queries, not concatenate a string, this is very dangerous for your system facilitating SQL injections.
Validate your values before attempting to query and validate the query returns.
if (Session["RgId"] != null && !String.IsNullOrEmpty(Session["RgId"].ToString()))
{
String sq = "select fullname,emailId from Registration where RgId = #RgId";
SqlCommand cmd1 = new SqlCommand(sq, con);
cmd1.Parameters.Add("#RgId", Convert.ToInt32(Session["RgId"].ToString()));
con.Open();
SqlDataReader rdr = cmd1.ExecuteReader();
if (rdr != null)
{
while (rdr.Read())
{
if (rdr["fullname"] != DBNull.Value && rdr["emailId"] != DBNull.Value)
{
Label4.Text = rdr["fullname"].ToString();
label5.Text = rdr["emailId"].ToString();
}
}
}
if (rdr != null)
{
rdr.Close();
}
con.Close();
}
Regards,
Andrew
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.
I have a database in which I created a table HUGO_BOSS. Its columns are [brand name], [stock quantity], [retail price] and its primery key is [Brand name]. I want to fill my textbox in windows form with the value of stock quantity present in my database. I tried the following code but it gives run-time error
The Connection was not close, the connection state is open.
if (comboBox2.Text == "HUGO BOSS")
{
try
{
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "Select [Stock quantity] as stockquantity from HUGO_BOSS WHERE [Brand name]=#name";
cmd.Parameters.AddWithValue("#name", comboBox3.SelectedItem);
con.Open();
OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
if (dr.Read())
{
textBox7.Text = dr["stockquantity"].ToString();
}
}
finally { con.Close(); }
}
One more thing, here I will select the primary key by using a combobox3
It looks you're trying to reuse a database connection that is already open.
You could try testing the connection state before trying to open it:
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "Select [Stock quantity] as stockquantity from HUGO_BOSS WHERE [Brand name]=#name";
cmd.Parameters.AddWithValue("#name", comboBox3.SelectedItem);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
if (dr.Read())
{
textBox7.Text = dr["stockquantity"].ToString();
}
Alternatively, you could create a new connection each time you need to execute a new command.