Hi i'm trying to changing the password so the user's password is update on the database. For example, i want the user Mary Tan's password to be changed from 12345 to 54321. But if affect the rest of the user's password. I really idk how to fix it.
Output:
click here
Table
database table
My Code:
protected void btnChangePassword_Click(object sender, EventArgs e)
{
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd";
if (Session["Username"] != null)
{
sql += " WHERE UserName='" + Session["Username"].ToString() + "'";
}
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
conn.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if(rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch(Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
Which means your Session["Username"] is null at this moment of execution. Hence the Where condition will skip and update all rows. And What is the Function of Reader There? It is not necessary, The ExecuteNonQuery is enough to do this Job and it will returns the number of rows affected. So you can do this in the following way:
string connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
if (Session["Username"] != null)
{
string sql = "UPDATE Staff Set Password=#NewPwd WHERE UserName=#Username";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#Username", Session["Username"]);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
}
}
else
{
// Show message that Session is Empty Can't Proceed
}
Important Note :- Don't save password as plain Text, Hash and salt them
Change your method like this (check Session in the start)
protected void btnChangePassword_Click(object sender, EventArgs e)
{
if (Session["Username"] == null)
{
//User is not logged-in. Display message or handle
return;
}
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd Where UserName = #UserName";
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#UserName", Session["Username"].ToString());
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
Related
Trying to update the first name of the student there is a textbox "FirstNameTextbox" information was loaded to it from the DB, when I change the information in the textbox and try to write the changes it read only the original data.So if it loaded "Craig" as the first name from the DB, i would edit and put "Chris" in the textbox, what happens is that Craig is written to the DB and not "Chris"
int stuID = getSqlStuID(IDNUMLabel.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlUpdateStudent = "Update tblStudent set fname = #fname where stuID = #stuID";
SqlCommand cmd = new SqlCommand(sqlUpdateStudent, conn);
conn.Open();
cmd.Parameters.AddWithValue("#stuID", stuID);
cmd.Parameters.AddWithValue("#fname", FirstNameTextbox.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Text = "Success";
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
IDNUMLabel.Text = Session["User"].ToString();
getStuData(Session["User"].ToString());
}
else
{
Response.Redirect("../Login/Login.aspx");
}
}
private void getStuData(string id)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select fname, sname From tblStudent Where idnumber = '" + id + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader selectedRecord = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
while (selectedRecord.Read())
{
FirstNameTextbox.Text = selectedRecord["fname"].ToString();
LastNameTextbox.Text = selectedRecord["sname"].ToString();
}
selectedRecord.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//id = 0;
//string msg = "Error reading Student ID";
//msg += ex.Message;
//throw new Exception(msg);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
At what point do you make the actual update? After a button was pressed, after the value was entered on the textbox...? You're missing the method in which the code that handles the update is placed...
Maybe this could help: How to display data from database into textbox, and update it
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Basically I am writing some code for update the profile only. But i got this error and it says "Object reference not set to an instance of an object". But I've been trying to find this error for 2 days but still I stuck on this error. Please help me the solve this error :( Thanks..
Output:
view output
Asp.net.cs code:
public partial class EditProfile : System.Web.UI.Page
{
SqlConnection conn = null;
SqlCommand cmd = null;
string connectionString = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "SELECT * FROM Staff";
string id = Session["StaffId"].ToString();
Session["StaffId"] = id;
try
{
cmd = new SqlCommand(sql, conn);
conn.Open();
dr = cmd.ExecuteReader();
dr.Read();
id = dr["StaffId"].ToString();
tbStaffName.Text = dr["StaffName"].ToString();
tbPassword.Text = dr["Password"].ToString();
tbEmail.Text = dr["Email"].ToString();
tbPhoneNo.Text = dr["PhoneNo"].ToString();
ddlTitle.SelectedItem.Text = dr["Title"].ToString();
dr.Close();
}
catch (Exception ex)
{
lblOutput.Text = "Error Message:" + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff SET Username=#username, Password=#Pwd, StaffName=#staff, Email=#email, PhoneNo=#phone, Title=#title ";
sql += " WHERE StaffId=#id";
string title= ddlTitle.SelectedItem.Text;
string id = Session["StaffId"].ToString();
Session["StaffId"] = id;
string username = Session["Username"].ToString();
Session["Username"] = username;
try
{
cmd = new SqlCommand(sql, conn);
if(username != null)
{
cmd.Parameters.AddWithValue("#username", username);
}
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#staff", tbStaffName.Text);
cmd.Parameters.AddWithValue("#Pwd", tbPassword.Text);
cmd.Parameters.AddWithValue("#email", tbEmail.Text);
cmd.Parameters.AddWithValue("#phone", tbPhoneNo.Text);
cmd.Parameters.AddWithValue("#title", title);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.Text = "Record update successfully";
}
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
try
{
SqlDSEditProfile.Update();
lblOutput.Text = "Application update";
}
catch (Exception ex)
{
lblOutput.Text = ex.Message;
}
}
}
You are not doing a null check on any of the Sessions. If StaffId or Username do not exists it will throw that error. Try this first.
string id = String.Empty;
if (Session["StaffId"] != null)
{
id = Session["StaffId"].ToString();
}
Session["StaffId"] = id;
string username = String.Empty;
if (Session["Username"] != null)
{
username = Session["Username"].ToString();
}
Session["Username"] = username;
When I enter user name and password, it logs in successfully and also opens desired field but when I enter wrong name or password (not saved in DB) it shows nothing actually it should encounter "else" this is the code
private void signin_button_Click(object sender, EventArgs e)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= D:/Student_Managment_System/SMS1.mdb";
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
string usrname = name_textBox.Text;
string passwd = pass_textBox.Text;
OleDbCommand cmd1 = new OleDbCommand("select * from Manager where Name='" + usrname + "' and Passwd='" + passwd + "'");
OleDbDataReader Reader = cmd1.ExecuteReader();
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
else
{
MessageBox.Show("Inviled User name or password");
}
}
myConnection.Close();
}
Your else statement isn't executed because there are no values to read when an invalid username or password is entered. You need to check if your reader has any rows. See here
Code
//Are there any rows
if(Reader.HasRows)
{
//If so read them
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
}
}
else
{
MessageBox.Show("Inviled User name or password");
}
This code is from our user login profile for our SAD project. The account I register for user log in is working since it saved in the database but I can't log in because it says invalid.
private void btn_login_Click(object sender, EventArgs e)
{
conn = new MySqlConnection(myconn);
string query = "select * from southpoint_school.user where userUsername='" + textBox1.Text + "' and userPassword='" + textBox2.Text + "'";
conn.Open();
cmd = new MySqlCommand(query, conn);
MySqlDataReader reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count++;
}
if (count == 1)
{
conn = new MySqlConnection(myconn);
string problem = "SELECT userAccountType from southpoint_school.user WHERE userUsername ='" + textBox1.Text + "'";
conn.Open();
cmd = new MySqlCommand(problem, conn);
string answer = cmd.ExecuteScalar().ToString();
conn.Close();
MessageBox.Show("Login successful!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (answer == "Administrator")
{
memorable = "Administrator";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
else
{
memorable = "Limited";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
}
else if (textBox1.Text == "" && textBox2.Text == "")
{
MessageBox.Show("No Username and/or Password Found!");
}
else
{
MessageBox.Show("Invalid Username And/Or Password!");
}
conn.Close();
}
The case
Invalid Username And/Or Password!
can only happen when you have 0 ore more than 1 search results in your southpoint_school.user database with your entered username + password. So I would inspect the data in your database.
Additionally I would
use parameters instead of string-concatenation for creating sql statements to avoid injection
save (salted)hashed passwords instead of plaintext in your database
use using statements for more effecient ressurce useage
query the user-table only once and use the result twice
e.g.:
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("No Username and/or Password Found!");
}
else
{
DataTable dtResult = new DataTable();
string Command = "select * from southpoint_school.user where userUsername=#un and userPassword=#up";
using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
{
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#un", textBox1.Text));
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#up", textBox2.Text));
myDataAdapter.Fill(dtResult);
}
}
if (dtResult.Rows.Count == 1)
{
MessageBox.Show("Login successful!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
if ((string)dtResult.Rows[0]["userAccountType"] == "Administrator")
{
memorable = "Administrator";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
else
{
memorable = "Limited";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
}
else if (dtResult.Rows.Count == 0)
{
MessageBox.Show("Invalid Username And/Or Password!");
}
else //TODO: treat the case for multiple results
{
}
}
i'm creating a login form for my system and want to add a User and Admin account. what i did in my database is to create a table for my users with a specific user type U_Type would be either 1 = admin or 2 = user.
i want to add an if statement that would call my column name U_Type and compare it either 1 or 2. below is my unfinished code. i'm using visual studio 2008 c# and ms sql 2005
here is my code:
float Outcome;
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
conn.Open();
String txtUser = textBox1.Text;
String txtPass = textBox2.Text;
string query = "SELECT * FROM tblUsers WHERE U_Name=#U_Name AND U_Pass=#U_Pass AND U_Type=#type";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(new SqlParameter("#U_Name", txtUser));
cmd.Parameters.Add(new SqlParameter("#U_Pass", txtPass));
cmd.Parameters.Add(new SqlParameter("#type", type));
SqlDataReader dr = cmd.ExecuteReader();
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
else if (textBox2.Text.Trim().Length == 0)
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
else if (dr.HasRows == true)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
if ()
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
}
i want the if statement to be here
else if (dr.HasRows == true)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
if ("#type"==1)
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
}
i really don't know the proper syntax for it. help me please i would really appreciate it. thank you
You have, roughly, the right idea, but your implementation is off.
You're validating the text boxes after you send the SQL query but before you check the results, and you're also passing in the type of the user.
The user type should be stored in the database along with the user, and you can return the type of user for the matching row (based on username and password). And your syntax is way off in some places.
A simplified approach based on what you appear to be doing would be something like this:
Do validation on the text boxes before executing the command. If validation passes, then select the row that matches the user name and password, and process the results accordingly:
private void button1_Click(object sender, EventArgs e)
{
bool validInput = false;
if (!String.IsNullOrWhitespace(textBox1.Text))
{
validInput = true;
}
else
{
MessageBox.Show("Please enter a user name.");
}
if (!String.IsNullOrWhitespace(textBox2.Text))
{
validInput = true;
}
else
{
MessageBox.Show("Please enter a password.");
}
if (validInput)
{
using (SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True"))
{
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM tblUsers WHERE U_Name = #U_Name AND U_Pass = #U_Pass", conn);
command.Parameters.Add("#U_Name", SqlDbType.VarChar).Value = textBox1.Text;
command.Parameters.Add("#U_Pass", SqlDbType.VarChar).Value = textBox2.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
string userType = reader["U_type"].ToString();
if (userType == "1")
{
// Handle regular users
}
else if (userType == "2")
{
// Handle admin users
}
}
else
{
MessageBox.Show("Login failed.");
}
}
}
}
}
The above code illustrates the approach. If both text boxes have text in them, the validInput flag is set to true. The connection is then opened, the command and parameters are set, the command is executed and a reader returned. If the reader has rows (meaning 1 or more records that matched the username and password are found), the reader is advanced to the first record (there should be only one match for a given username/password combination).
The "U_type" column is interrogated to see if it's a regular user or an admin user, and the user is processed accordingly.
It's not clear from your posted code whether "U_type" is a string or an integer; if it's an integer you'll need to convert it like this:
int userType = Convert.ToInt32(reader["U_type"]);
And change the corresponding if checks:
if (userType == 1)
and
if (userType == 2)
If you want to authenticate user and compare the Type then return DataTable.
public DataTable ValidateUser(string username,string password)
{
DataTable dt = new DataTable();
SqlCommand cmd; SqlDataReader dr;
SqlConnection con = new SqlConnection(yourConnectionString);
try
{
cmd = new SqlCommand();
cmd.CommandText = "Select * from tblUsers where U_Name=#U_Name and U_Pass=#U_Pass";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#U_Name", username);
cmd.Parameters.AddWithValue("#U_Pass", password);
cmd.Connection = con;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
dr = cmd.ExecuteReader();
dt.Load(dr);
}
catch (Exception ex)
{
dt = null;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close(); con.Dispose();
}
}
return dt;
}
Calling ValidateUser Method:
DataTable dt=new DataTable();
dt=ValidateUser();
if(dt!=null && dt.Rows.Count>0)
{
if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==1)
{
//show form for user where utpe=1
}
else if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==2)
{
//show form for user where utype=1
}
else
{
//otherstuff
}
}
else
{
//invwalid user
}
hopethis helps