Select password field and show it in textbox by criteria - c#

I have a windows form with 4 textbox fields: username, question, date of birth, and password.
I want to load and display the password from the database table if the entered informations are correct (username, question and dateOfBirth textbox) and the OK button is pressed.
SqlConnection myConn = new SqlConnection(myConnection);
SqlCommand SelectCommand = new SqlCommand("select PassWord from dbo.Admin where UserName = '" + this.UserName.Text + "' and Question= '" + this.Question.Text + "' and DateOfBirth= '" + this.DateOfBirth.Text + "';", myConn);
SqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
PassShow.Text = myReader["PassWord"].ToString();
myConn.Close();
I use VS 2015, writing this in c# with db from VS.
I have this error when i debug it:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: Invalid attempt to read when no data is present.

If you only want to return one row and one column, use this instead:
PassShow.Text = SelectCommand.ExecuteScalar()?.ToString();
Otherwise you have to check if the reader got any result rows before you can access them savely:
using (SqlDataReader myReader = SelectCommand.ExecuteReader())
{
if (myReader.HasRows && myReader.Read())
PassShow.Text = myReader.GetString("PassWord");
}

This worked perfectly for me:
myReader = SelectCommand.ExecuteReader();
if (myReader.HasRows && myReader.Read())
{
PassShow.Text = (myReader["PassWord"].ToString());
}
myConn.Close();

Related

database INNER JOIN

These are the two set up tables
LOGIN TABLE
USER'S NAME
I want to create something like the User will key in their USER_ID and USER_PWD in a textbox. IF the user successfully login, it will say " HI + PATNAME ".
I have created this code so far but it isnt working.
string sqlStr = "Select patpro.'PATNAME' FROM patpro,useform where USER_ID=#name and USER_PWD=#password and useform.'USER_ID' = patpro.'USERID'";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Password);
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.HasRows)
{
login.Read();
string name = (login["USER_ID"].ToString());
txtAssignID1.Text = "Login verified. Hi, " + name + "\n";
}
From what I see, you're trying to use login["USER_ID"].ToString() which USER_ID is a nonexistent column definition inside current SELECT statement. Hence, you should add column names which defined in SELECT results like login["PATNAME"] and use proper INNER JOIN statement instead:
string sqlStr = #"SELECT patpro.PATNAME FROM patpro INNER JOIN useform
ON useform.USER_ID = patpro.USERID
WHERE useform.USER_ID = #name AND useform.USER_PWD = #password";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Password);
cmd.CommandText = sqlStr;
cmd.Connection = connection;
connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.HasRows)
{
// read value inside the loop, because MySqlDataReader is forward-only
while (login.Read())
{
string name = login["PATNAME"].ToString();
txtAssignID1.Text = "Login verified. Hi, " + name + "\n";
}
}
Additional note: Better to use using statement for MySqlConnection, MySqlCommand and MySqlDataReader to ensure immediate disposal of MySQL connection objects after fetching query results.

Update ExceptionNonQuery

I am trying to update an MS Access table and it keeps throwing an error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in string in query expression 'EmID = '234'.
The EmID is in the database. Please help
public partial class Sales : Form
{
...
private void btnUpdate_Click(object sender, EventArgs e)
{
int EmpID = int.Parse(txtEmpID.Text);
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\SalesData.mdb");
OleDbCommand update = new OleDbCommand("UPDATE Sales SET Printer = '" + txtPrinter.Text + "', Ink = '" +txtInk.Text + "', Paper = '"+txtPaper.Text+"' WHERE EmID = '" + txtEmpID.Text + " ", con);
con.Open();
update.ExecuteNonQuery();
con.Close();
MessageBox.Show("Sales Updated");
}
...
}
You have forgotten to add a closing quote after the WHERE value. But fixing the problem adding the missing quote serves only to hide other problems.
What if one of your textboxes contains a single quote? You will get again a syntax error exception caused by the string concatenation where the quotes serve as delimiter of your values. With a single quote typed by your user you will confuse the Sql Parser again.
To fix this problem (and a more serious one called Sql Injection) you need to start using parameters
string cmdText = #"UPDATE Sales SET Printer = #printer,
Ink = #Ink, Paper = #Paper
WHERE EmID = #id";
using(OleDbConnection con = new OleDbConnection(...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("#printer", OleDbType.VarWChar).Value = txtPrinter.Text;
cmd.Parameters.Add("#ink", OleDbType.VarWChar).Value = txtInk.Text;
cmd.Parameters.Add("#paper", OleDbType.VarWChar).Value = txtPaper.Text;
cmd.Parameters.Add("#id", OleDbType.VarWChar).Value = txtEmpID.Text;
cmd.ExecuteNonQuery();
}

data not being updated to table

I'm trying to implement a password change feature but it doesn't seem to want to work.
private void button3_Click(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb"))
{
DataTable dt = new DataTable();
con.Open();
errorProvider1.Clear();
if (dt.Rows[0][0].ToString() == "1")
{
if (textBox3.Text == textBox4.Text)
{
OleDbDataAdapter da = new OleDbDataAdapter(" COUNT (*) FROM login WHERE username= '" + textBox1.Text + "' AND [password]='" + textBox2.Text + "' ", con);
OleDbCommand com = new OleDbCommand("UPDATE login SET [password] = '" + textBox3.Text + "' WHERE username = '" + textBox2.Text + "'", con);
com.ExecuteNonQuery();
MessageBox.Show("password successfully changed", "success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
errorProvider1.SetError(textBox3, "passwords dont match");
errorProvider1.SetError(textBox4, "passwords dont match");
}
}
else
{
errorProvider1.SetError(textBox1, "wrong username");
errorProvider1.SetError(textBox2, "wrong pasword");
}
}
}
there is an error in the line if (dt.Rows[0][0].ToString() == "1") where it states that no data was found at that position, yet there are 5 rows in the data table.
when the code is run without the above line, as in //if (dt.Rows[0][0].ToString() == "1")
the code runs but no data is being updated in the table.
updated code again and still recived the same error:
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM login WHERE username= '" + textBox1.Text + "' AND [password]='" + textBox2.Text + "' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Open();
errorProvider1.Clear();
if (dt.Rows[0][0].ToString() == "1")
Try filling your DataTable as following -
string cmdString = "SELECT * FROM login WHERE username= '" + textBox1.Text + "' AND [password]='" + textBox2.Text + "' ";
OleDbCommand cmd = new OleDbCommand(cmdString,con);
con.Open();
var dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
con.Close()
Now you should get your data in table, provided that your select query is correct. Make sure you use using blocks on connection and command objects to dispose these when they are out of scope.
you are just declaring data table,not assigning any data
DataTable dt = new DataTable();
thats why when you try to get dt.Rows[0][0].ToString() it gives error
As you can try this:
OleDbDataAdapter custDA = new OleDbDataAdapter();
DataSet custDS = new DataSet();
DataTable custTable = new DataTable("Customers");
custTable.Columns.Add("CustomerID", typeof(String));
custTable.Columns.Add("CompanyName", typeof(String));
custDS.Tables.Add(custTable);
//Use ADO objects from ADO library (msado15.dll) imported
// as.NET library ADODB.dll using TlbImp.exe
ADODB.Connection adoConn = new ADODB.Connection();
ADODB.Recordset adoRS = new ADODB.Recordset();
adoConn.Open("Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;", "", "", -1);
adoRS.Open("SELECT CustomerID, CompanyName FROM Customers", adoConn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
custDA.Fill(custTable, adoRS);
adoRS.Close();
adoConn.Close();
You can follow this reference
As noted by another, you never assign a value to the data table, that is why it is choking. Your query itself, by string concatenation will open you to SQL-Injection. Parameterize it. Finally, for your query, I would query all records for a given user ID, but get the user and password values based on only qualifying the user ID, not the password. This way, if you have more than 1 row returned, it will indicate duplicate user accounts and should get special attention. If it returns NO rows, then no such user. If it returns ONE row, then you can compare to the password entered and if matched, you have your correct user ID to run with.
starting with your
using( OleDbConnection con = ...)
{
// create command first.. Parameterize it. In this case "#" is parameter indicator
// for Access. parmUserName is the parameter name to be applied. I explicitly added
// "parm" in front to ensure differentiation between the parameter and actual column.
var cmd = new OleDbCommand(
#"select password from login where username = #parmUserName", con);
// Now, add the parameter of proper data type. The name of the parameter and it's value
cmd.Parameters.AddWithValue("parmUserName", textBox1.Text);
// create your data adapter now based on the command above
var da = new OleDbDataAdapter(cmd);
// NOW, create your data table object and have data adapter query and fill with rows.
var dt = new DataTable();
da.Fill(dt);
// NOW, check results.
if (dt.Rows.Count == 0)
MessageBox.Show("No such user account");
else if( dt.Rows.Count > 1)
MessageBox.Show("Duplicate user account");
else
{
// valid single record. Do the passwords match?
if (textBox3.Text.Equals(dt.Rows[0]["password"].ToString()))
{
MessageBox.Show("Valid login, allow to continue");
// Now, since it appears you are trying to UPDATE the password for the user,
// build new UPDATE command and parameterize it in a similar fashion
var cmdUpd = new OleDbCommand(
#"update login set password = #parmNewPwd where username = #parmUserName", con);
// Now, add the parameter of proper data type. The name of the parameter and it's value
cmd.Parameters.AddWithValue("parmNewPwd", textBox3.Text);
cmd.Parameters.AddWithValue("parmUserName", textBox1.Text);
if (cmd.ExecuteNonQuery() == 1)
MessageBox.Show("Password updated");
else
MessageBox.Show("Failed updating password");
}
else
MessageBox.Show("Invalid password");
}
}
FINAL NOTE. You should also look into cleaning data especially before building SQL commands. Never concatenate strings where users can manually enter data for SQL-Injection, parameterize them.

How to get/display the user-information after logging in. ASP.net C#

I am implementing an online voting system for my school-project.
After the voter's log-in, i want to display their name, and ID in the label control at the content body. I try to use SESSION to store the voter's username in the log-in page but I'm not sure of my syntax because nothings happen.
I want to know the other way of retrieving a data from database! Please teach me.
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Session["VotersID"] + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Please Help Me. Thanks! -
#Honey Maglangit , what you use is PARAMETER not SESSION.
Response.Redirect("VoterPage.aspx?VotersID="+VoterUsername.Text);
So, you should get your VotersID by this way:
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Request.QueryString["VotersID"].ToString() + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Try it again.
You can use LogonUserIdentity as follow
if (Request.LogonUserIdentity.IsAuthenticated)
lblName.Text = Request.LogonUserIdentity.Name;
just add this namespace:
using Microsoft.AspNet.Identity;
then you can get LoggedInUserId by:
User.Identity.GetUserId();
Or
HttpContext.Current.User.Identity.GetUserId();
So you don't need to use session to keep UserId.
Also you can create Custom Identity and instead of save Username in Name property, storing custom string Store User Data in ASP.NET Identity
get session data and send to one page(register.aspx) to another page(user_home.aspx)
Session["remail2"] = txtemailsignin.Text;
Server.Transfer("user_home.aspx", true);
display the user-information after logging
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["socailweb"].ConnectionString);
string sql = "select * from tblUsers where remail='" + Session["remail2"] + "'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sqldr = cmd.ExecuteReader();
if (sqldr.Read() == true)
{
lblVotersID.Text = sqldr.GetValue(2).ToString();
lblVoterName.Text = sqldr.GetValue(3).ToString();
}
sqldr.Close();
con.Close();

syntax error in from clause C# and Access

I keep getting this run time error, syntax error in from clause. I tried already using my sql query in access and it seems ok.
Here's my code and I am using C# windows form with text box and button
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Misry27\Documents\Visual Studio 2010\Projects\Inventory\Inventory\bin\Debug\Inventory.mdb");
OleDbCommand cmd = new OleDbCommand("select * from Employee where username = '" + this.tbUsername.Text + "' and password = '" + this.tbPassword.Text + "';", conn);
OleDbDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username or Password is correct");
}
else
{
MessageBox.Show("Username or Password Incorrect");
}
conn.Close();
As explained in the comments above, PASSWORD is a reserved keyword and need to be enclosed in square brackets when used in query executed from net.
The usual advice follows. Use parameterized query to avoid parsing problem and sql injections, use the using statement around your disposable objects.
using(OleDbConnection conn = new OleDbConnection(a correct connection string here))
using(OleDbCommand cmd = new OleDbCommand(#"select * from Employee
where username = ? AND [Password] = ?", conn);
{
conn.Open();
cmd.Parameters.AddWithValue("#p1", this.tbUsername.Text);
cmd.Parameters.AddWithValue("#p2", this.tbPassword.Text);
using(OleDbDataReader dr = cmd.ExecuteReader())
{
.....
}
}

Categories

Resources