This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I was wondering if somebody could point me in the right direction.My program has 1 dropdown list, 2 text boxes and 2 buttons.
namespace passwordReset
{
public partial class Form1 : Form
{
//variables to mess with the password
public string password1;
public string password2;
public string username;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(xxxxxxx);
connection.Open();
string query = "select Login, Password from Employees order by Login desc";
SqlDataAdapter da = new SqlDataAdapter(query, connection);
DataSet ds = new DataSet();
da.Fill(ds, "Credentials");
ddlLogin.DisplayMember = "Login";
ddlLogin.ValueMember = "Password";
ddlLogin.DataSource = ds.Tables["Credentials"];
connection.Close();
}
private void ddlLogin_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLogin.SelectedItem != null)
{
DataRowView drv = ddlLogin.SelectedItem as DataRowView;
//MessageBox.Show("The username you selected is: " + drv.Row["Login"].ToString());
//MessageBox.Show("The password you selected is: " + drv.Row["Password"].ToString());
//MessageBox.Show("username selected is: " + ddlLogin.Text.ToString());
//MessageBox.Show("password is: " + ddlLogin.SelectedValue.ToString());
}
}
private void txtPassword1_TextChanged(object sender, EventArgs e)
{
password1 = txtPassword1.Text;
}
private void txtPassword2_TextChanged(object sender, EventArgs e)
{
password2 = txtPassword2.Text;
}
private void btnReset_Click(object sender, EventArgs e)
{
if (ddlLogin.Text == "rruales" || ddlLogin.Text == "xxxxx" || ddlLogin.Text == "xxxxxx")
{
MessageBox.Show("Cannot change this user's password");
}
if (password1 == password2 && ddlLogin.Text != "rruales" && ddlLogin.Text != "xxxxx" && ddlLogin.Text != "xxxxx")
{
string newPassword = txtPassword2.Text;
username = ddlLogin.Text.ToString();
string currentPassword = ddlLogin.SelectedValue.ToString();
currentPassword = newPassword;
SqlConnection connection = new SqlConnection(xxxxxxxx);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Employees SET [Password] = #password WHERE [Login] = #login";
cmd.Parameters.AddWithValue("#password", currentPassword);
cmd.Parameters.AddWithValue("#login", username);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Password successfully updated");
connection.Close();
}
else
{
MessageBox.Show("You either choose usernames rruales or xxxxx or xxxx, or the passwords don't match, try again");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
The code does what it needs to do, when a user selects a user name from the dropdown menu, they can reset the user's password.But if the user types the username they want to reset, I get an error here:
string currentPassword = ddlLogin.SelectedValue.ToString();
the error says Object reference not set to an instance of an object.use the "new" keyword to create an object instance.I understand the error is coming from the fact that the user is inputting the username instead of selecting it. my question is and I don't need code, I want to understand how I can go ahead and handle that, where the user wants to just type the username or pick it from the dropdown?any advise to rewrite the code is welcome, I am an entry level developer.
update, I can't answer my own question, but it works now thanks all
All,
thank you for your help.
what you all said worked, and I also had to do 1 change to my code, I realized I was doing something very dumb:
private void txtPassword1_TextChanged(object sender, EventArgs e)
{
password1 = txtPassword1.Text;
}
private void txtPassword2_TextChanged(object sender, EventArgs e)
{
password2 = txtPassword2.Text;
}
private void btnReset_Click(object sender, EventArgs e)
{
if (ddlLogin.SelectedValue == null)
{
username = ddlLogin.Text.ToString();
}
else
{
username = ddlLogin.Text.ToString();
}
if (ddlLogin.Text == "rruales" || ddlLogin.Text == "xxxxx" || ddlLogin.Text == "xxxxxx")
{
MessageBox.Show("Cannot change this user's password");
}
if (password1 == password2 && ddlLogin.Text != "rruales" && ddlLogin.Text != "xxxxxx" && ddlLogin.Text != "xxxxxx")
{
string newPassword = txtPassword2.Text;
//username = ddlLogin.Text.ToString();
// string currentPassword = ddlLogin.SelectedValue.ToString();
currentPassword = newPassword;
SqlConnection connection = new SqlConnection(xxxxxx);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Employees SET [Password] = #password WHERE [Login] = #login";
cmd.Parameters.AddWithValue("#password", currentPassword);
cmd.Parameters.AddWithValue("#login", username);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Password successfully updated");
connection.Close();
}
else
{
MessageBox.Show("You either choose usernames rruales or xxxxx or xxxx, or the passwords don't match, try again");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I don't know why I did this:
string currentPassword = ddlLogin.SelectedValue.ToString();
If you don't select an item from the DropDown, it's SelectedValue will be null. You should check if it's null. If it is null then get the value from the textbox.
string userName;
if (ddlLogin.SelectedValue == null) {
userName = theTextBox.Text;
} else {
username = theDropDownList.SelectedValue.Text;
}
I'm not sure if it's the username you're trying to get. You mention the exception throws when you type the username but you grab a password from ddlLogin? Whatever you're trying to assign, just check if the dropdown is null like above and assign to the correct variable.
Related
I got stuck after couple of hours of research. I'm trying to make a basic Universal Windows App with login form - after clicking a button, credentials in textboxes are checked with remote MySQL database. If valid, app shoud navigate to another specified page. If not, error message is displayed.
I can't find error in my code below. After clicking the button Windows' blue circle spins and after couple of seconds returns to VS2017. No errors and warnings. State.ToString() returns 'Open' so I do have a connection with DB. What I'm doing wrong?
public sealed partial class MainPage : Page
{
const string connString = "server=my_server;pwd=pass;uid=user_id;database=mydb;persistsecurityinfo=True";
MySqlConnection conn = new MySqlConnection(connString);
public MainPage()
{
this.InitializeComponent();
}
private void DbConnection()
{
try
{
conn.Open();
}
catch (MySqlException e)
{
throw;
}
}
private bool DataValidation(string user, string pass)
{
DbConnection();
MySqlCommand cmd = new MySqlCommand("SELECT Username, Password FROM Users WHERE Username=#user AND Password=#pass;");
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = conn;
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
string user = UserTextBox.Text;
string pass = PassTextBox.Text;
if (user == "" || pass == "")
{
StatusTextBlock.Text = ("No emty fields allowed. Try again...");
return;
}
bool loginSuccessful = DataValidation(user, pass);
if (loginSuccessful)
{
this.Frame.Navigate(typeof(Page2), null);
}
else
{
StatusTextBlock.Text = "Invalid e-mail or password. Try again...";
}
}
}
Complete working solution:
using MySql.Data.MySqlClient;
namespace Project
{
public sealed partial class MainPage : Page
{
const string connString = "server=server_name;user id=uid;pwd=password;persistsecurityinfo=True;database=db_name";
public MainPage()
{
this.InitializeComponent();
}
private bool DataValidation(string user, string pass)
{
using (MySqlConnection conn = new MySqlConnection(connString))
using (MySqlCommand cmd = new MySqlCommand("SELECT " +
"Username, Password " +
"FROM users " +
"WHERE Username=#user AND Password=#pass;", conn))
{
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = conn;
cmd.Connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
}
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
string user = UserTextBox.Text;
string pass = PassBox.Password;
if (user == "" || pass == "")
{
StatusTextBlock.Text = ("Your text");
return;
}
bool loginSuccessful = DataValidation(user, pass);
if (loginSuccessful)
{
this.Frame.Navigate(typeof(Page2), null);
}
else
{
StatusTextBlock.Text = "Your text";
}
}
}
}
bellow my code is perfectly fine and working but I want to check if connec.reader.HasRows then redirect the user to page.aspx else pop up a message with "you have not registered". Please can anyone help me why is this not working. Help is appreciated.
This Code is from my Manager Class.
public static void Insert(string _username, string _password)
{
Connection connec = new Connection();
connec.SqlQuery("select * from manager where UserName='#username' AND Password='#password'");
connec.cmd.Parameters.AddWithValue("#username", _username);
connec.cmd.Parameters.AddWithValue("#password", _password);
connec.QueryReader();
}
The code bellow is from page.aspx page to act upon the method.
protected void Button1_Click(object sender, EventArgs e)
{
ManagerClass connec = new ManagerClass();
ManagerClass.Insert(TextBox1.Text, TextBox2.Text);
}
It's the code structure which you need to correct. Instead of void Insert method you should have method bool IsValidUser as following. Also this method need not be static method. It should be instance method.
public bool IsValidUser(string _username, string _password)
{
Connection connec = new Connection();
connec.SqlQuery("select COUNT(*) from manager where UserName=#username AND Password=#password");
connec.cmd.Parameters.AddWithValue("#username", _username);
connec.cmd.Parameters.AddWithValue("#password", _password);
int userCount = (int) sqlCommand.ExecuteScalar();
con.Close();
cmd.Dispose();
return userCount != 0;
}
Now in your page you call this method and check the value returned by the method. If it's false then show message else redirect user to the page.aspx.
protected void Button1_Click(object sender, EventArgs e)
{
ManagerClass managerObj = new ManagerClass();
if(managerObj.IsValidUser(TextBox1.Text, TextBox2.Text))
{
Response.Redirect("page.aspx");
}
else
{
//Show message "you have not registered";
}
}
if (TextBox1.Text != string.Empty && TextBox2.Text != string.Empty)
{
Connection connec = new Connection();
SqlCommand cmd = new SqlCommand("SELECT * FROM manager WHERE userName=#userName and password=#password", connec);
cmd.Parameters.AddWithValue("#userName", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
// do something here. (ex: get logs/date/session datas)
}
else
{
// you have not registered! (Show your warning message here)
Response.Redirect("register.aspx"); //(or use your popup here)
}
con.Close();
cmd.Dispose();
Response.Redirect("page.aspx");
}
else
{
// _userName and _password cannot be null! (your message here)
}
I am currently creating a voting system whereby existing users can vote on whether other entries are valid or not (upvote/Downvote) thru a sql dataset table.
Each user who is registered gets a customer number and the user needs a customer number to cast a vote. When the user casts a vote their customer number is recorded in the entry and the sql query updates the score to either add 1 to upvote or 1 to downvote. A unique constraint is applied to the voters ID on each entry voted to prevent a double vote and a user must have a customer number to vote.
My Code below attempts to do this however it always seems to end up with the message box saying "error, you cannot vote until you provide a valid customer number in the Textbox". All help is appreciated, thanks a lot!
protected void searchTheDB()
{
string s = "SELECT compName As 'Company/Organization Name', btcAddr As 'Bitcoin Address', Premium_User as 'Premium User'," +
"upvote as 'Upvotes',downvote As 'Downvotes' FROM clientDataTable WHERE compName LIKE '%" + searchBox.Text + "%'";
try
{
SqlConnection forSearch = new SqlConnection(connectionString);
SqlDataAdapter search = new SqlDataAdapter(s, forSearch);
DataSet dB = new DataSet();
search.Fill(dB);
searchGridView.DataSource = dB;
searchGridView.DataBind();
searchBox.Text = String.Empty;
}
catch (SqlException exp)
{
throw new InvalidOperationException("Sorry, the website is experiencing difficulties, please try again, error: ", exp);
}
}
protected void searchButton_Click(object sender, EventArgs e)
{
custVoteTextBox.Text = String.Empty;
searchTheDB();
generalLabel.Text = "results displayed below, if nothing is displayed your search returned no results";
}
protected void canUserVote()
{
submitCustNumButton_Click(new object(), new EventArgs());
string query = "INSERT INTO dbo.ClientDataTable (custNum) Values (#custNum)";
try
{
SqlConnection checkCustNum = new SqlConnection(connectionString);
SqlCommand isCustNumbValid = new SqlCommand(query, checkCustNum);
isCustNumbValid.Parameters.AddWithValue("#custNum", custNumber);
checkCustNum.Open();
isCustNumbValid.ExecuteNonQuery();
checkCustNum.Close();
}
catch (SqlException e)
{
if (e.Number == 2627) //checks if customer number is registered by activating unique constraint
{
canVote = true;
}
else //else user is not eligable to vote
{
canVote = false;
MessageBox.Show("invalid customer number, you cannot vote" + e);
}
}
}
protected void searchGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
canUserVote();//calls this method to check if user is eligable to vote with the given custNum in the textbox
if (canVote == true && custVoteTextBox.Text.Length == 8)
{
try
{
SqlConnection voteDb = new SqlConnection(connectionString);
{
switch (e.CommandName)
{
case "Upvote":
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = searchGridView.Rows[index];
string upvoteUpdateQuery = "UPDATE dbo.clientDataTable SET upvote = #upvote WHERE compName = #compName";
SqlCommand Upvote = new SqlCommand(upvoteUpdateQuery, voteDb);
Upvote.Parameters.AddWithValue("#upvote", "#upvote" + 1);
Upvote.Parameters.AddWithValue("#compName", selectedRow.DataItem.Equals("#compName"));
string insertQuery = "INSERT INTO dbo.clientDataTable (voted) Values(#voted) WHERE compName = #compName";
SqlCommand insertVoterDetailsUpvote = new SqlCommand(insertQuery, voteDb); //inserts voter information into specific entries table
insertVoterDetailsUpvote.Parameters.AddWithValue("#voted", custNumber);
insertVoterDetailsUpvote.Parameters.AddWithValue("#compName", selectedRow.DataItem.Equals("compName"));
voteDb.Open();
Upvote.ExecuteNonQuery();
voteDb.Close();
break;
case "Downvote":
int downvoteindex = Convert.ToInt32(e.CommandArgument);
GridViewRow downvoteSelectedRow = searchGridView.Rows[downvoteindex];
string downvoteUpdateQuery = "UPDATE dbo.clientDataTable SET downvote = #downvote WHERE compName = #compName";
SqlCommand Downvote = new SqlCommand(downvoteUpdateQuery, voteDb);
Downvote.Parameters.AddWithValue("#downvote", "#downvote" + 1);
Downvote.Parameters.AddWithValue("#compName", downvoteSelectedRow.DataItem.Equals("#compName"));
string downvoteInsertQuery = "UPDATE clientDataTable SET downvote = downvote + 1 WHERE compName = #compName";
SqlCommand insertVoterDetailsDownvote = new SqlCommand(downvoteInsertQuery, voteDb); //inserts voter information into specific entries table
insertVoterDetailsDownvote.Parameters.AddWithValue("#voted", custNumber);
insertVoterDetailsDownvote.Parameters.AddWithValue("#compName", downvoteSelectedRow.DataItem.Equals("#compName"));
voteDb.Open();
Downvote.ExecuteNonQuery();
voteDb.Close();
break;
}
}
}
catch (SqlException exp)
{
if (exp.Number == 2627)
{
MessageBox.Show("Sorry, you have already voted");
}
else
{
throw new InvalidOperationException("Sorry, the website is experiencing difficulties, please try again, error: ", exp);
}
}
}
else
{
MessageBox.Show("error, invalid customer number in the Textbox");
}
}
protected void submitCustNumButton_Click(object sender, EventArgs e)
{
int custNo = int.Parse(custVoteTextBox.Text);
this.custNumber = custNo;
}
I can't tell for sure from your code but it seems that custNumber is a text box and so instead of:
if (canVote == true && custNumber.ToString().Length == 9)
you should have:
if (canVote == true && custNumber.Text.Length == 9)
If I'm wrong and it isn't a text box, put a breakpoint on that line and see what custNumber.ToString() actually equals.
Also note that your code is vulnerable to a SQL injection attack. Here's some interesting reading on the subject. How does the SQL injection from the "Bobby Tables" XKCD comic work?
hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?
I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx
I want to store a password in the database, but when I click Submit button, it added successfully to the database, but it does not stored the password in the database as random text, but as the original text. How could I fix this?
Here is the code that I am using:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
string myPassword;
string strHashedPassword;
string strStoredPassword;
int mySalt;
bool checking = false;
public Registration()
{
InitializeComponent();
}
private void Registration_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (this.textBox1.Text == "")
{
MessageBox.Show("Cannot be empty", "Warning", MessageBoxButtons.OK);
}
else
{
Checking _checking = new Checking();
_checking.ShowDialog();
checking = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (this.textBox1.Text == "" || this.textBox2.Text == "" || this.textBox3.Text == "" || this.textBox4.Text == "")
{
MessageBox.Show("Cannot be empty", "Warning", MessageBoxButtons.OK);
}
else
{
AddDatabase(sender, e);
}
}
private void AddDatabase(object sender, EventArgs e)
{
if (checking.Equals(false))
{
MessageBox.Show("You have to check first", "Warning", MessageBoxButtons.OK);
}
else
{
string query = "INSERT INTO [Member] ([Username], [Password], [UserType], [UserStore]) VALUES (#Username, #Password, #UserType, #UserStore)";
OleDbConnection _conn = new OleDbConnection(connectionString);
_conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, _conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = this.textBox2.Text;
cmd.Parameters.Add("#UserType", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserType"].Value = this.textBox3.Text;
cmd.Parameters.Add("#UserStore", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserStore"].Value = this.textBox4.Text;
cmd.ExecuteNonQuery();
DialogResult _dialogResult = MessageBox.Show("Added Successfully", "Success", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
this.Hide();
CreateRandomPassword();
this.Close();
}
}
}
}
private void CreateRandomPassword()
{
// Generate a new random password string
myPassword = this.textBox2.Text;
// Generate a new random salt
mySalt = Password.CreateRandomSalt();
// Initialize the Password class with the password and salt
Password pwd = new Password(myPassword, mySalt);
// Compute the salted hash
// NOTE: you store the salt and the salted hash in the database
strHashedPassword = pwd.ComputeSaltedHash();
strStoredPassword = strHashedPassword;
}
Thank you!
Your answer much appreciated!
You're using this.textBox2.Text for the #Password portion of the query, but your CreateRandomPassword() method only changes strStoredPassword and strHashedPassword (As an aside, I don't really see why you have 2 variables to hold the same value, it's redundant).
You should change
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = this.textBox2.Text;
to
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = strStoredPassword;
and move the call to CreateRandomPassword() up above the query execute.
In your "AddDatabase" function, change textbox value to "strStoredPassword"
like below
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = strStoredPassword;