enabling button upon textbox length condition c# - c#

I am trying to Enable BtnSubmit based on the length of TxtPswrd being greater than 8. I am using the Textfield Validating function, I am confused, should I used Validating, Validated or TextChanged functions?
private void BtnSignin_Click(object sender, EventArgs e)
{
// SqlConnection con = StartCon();
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox textBox = c as TextBox;
if (textBox.Text != string.Empty)
{
DataInserted(sender, e);
}
else
{
MessageBox.Show("Fill All Fields", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
TxtID.Focus();
break;
}
}
}
the DataInserted function:
private void DataInserted(object sener, EventArgs e)
{
try
{
SqlConnection sqlConnection = StartCon();
string AdminLookup = "Select count(*) from signin WHERE memid = '" + TxtID.Text + "' and adminpass='"+TxtPswrd.Text+"'";
SqlCommand command = new SqlCommand(AdminLookup, sqlConnection);
command.Parameters.Clear();
command.Parameters.AddWithValue("#usr", TxtUsername.Text);
command.Parameters.AddWithValue("#pwd", TxtPswrd.Text);
if (command.ExecuteScalar().ToString() =="1")
{
SetValueForText1 = TxtUsername.Text;
new Thread(() => new PSP_Manager().ShowDialog()).Start();
this.Close();
}
else
{
MessageBox.Show("Error Signing in", "Check Credentials", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SqlException sqlexception)
{
MessageBox.Show("Error", sqlexception.Message);
}
finally
{
StartCon().Close();
}
}
I am trying to enable the BtnSubmit only when the TxtPswrd.length >= 8
help, please.
pic

I'd use a TextChanged:
private void PasswordTextbox_TextChanged(object sender, EventArgs e){
submitButton.Enabled = passwordTextbox.Text.Length >= 8;
}
because I'd want the submit button to enable while they were still focused in the box, as soon as they'd typed 8 chars
In other news, don't write SQL commands like that; see http://Bobby-tables.com for why..
..and also don't store passwords in plaintext in a database; doing so is the reason http://haveibeenpwned.com has to exist

Related

Multiuser Login with login attempts tracked

I am a c# learner and need your help. Thanks in advance. I am working on this multi-user single login form. I have connected to SQL local database with the following as the columns:
UserID, Password, UserType
My problem is, the code below works fine as long as these three are correct. If I provide a wrong password for example, nothing happens.
It has to be an issue with the "Else" part of my code, but I have tried so many changes I have even lost track of when I was close to making it work. Please help.
To restate my expectations of the project:
1.When I select Admin or Student from combobox(cmbusertype) and provide INcorrect userid and password, I should get an incorrect credentials error message and number of attempts left.After 3 attempts, login button should be grayed out and I am prompted to reset my password.
public partial class Loginsystem : Form
{
public Loginsystem()
{
InitializeComponent();
}
int attempts =1;
private void btnlogin_Click(object sender, EventArgs e)
{
if (cmbusertype.SelectedItem == null)
{
MessageBox.Show("Please select User Type to continue...");
cmbusertype.Focus();
return;
}
if (txtuserid.Text == "")
{
MessageBox.Show("Please enter your UserID...");
txtuserid.Focus();
return;
}
if (txtpassword.Text == "")
{
MessageBox.Show("Please enter your password...");
txtpassword.Focus();
return;
}
try
{
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLlocaldb; Initial Catalog = AdminAuthentication; Integrated Security = True"); ;
SqlCommand cmd = new SqlCommand("select * from SimplifyLogin where userID='" + txtuserid.Text + "' and password='" + txtpassword.Text + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
string cmbItemValue = cmbusertype.SelectedItem.ToString();
if (dt.Rows.Count >0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["UserType"].ToString() == cmbItemValue) //you can use 2 instead of usertype in that index because usertype column is in 2 index
{
if (cmbusertype.SelectedIndex == 0)
{
MessageBox.Show("You are logged in as " + dt.Rows[i][2]);
MessageBox.Show("Displaying Admin Dashboard");
this.Hide();
}
else
{
MessageBox.Show("Welcome Student! Displaying Exam Options");
this.Hide();
}
}
else
{
MessageBox.Show("Invalid username and/or Password.Please try again. \nAttempts: " + attempts + "out of of 3");
txtpassword.Clear();
attempts++;
}
if (attempts == 4)
{
MessageBox.Show("You have reached maximum login attempts. Click 'Forgot Password' below to reset it.");
btnlogin.Enabled = false;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
i can customize this code because you have not to use for loop because number of rows which return from database will be one only so..
public partial class Loginsystem : Form {
public Loginsystem() {
InitializeComponent();
}
private int attempts = 1;
private void btnlogin_Click(object sender, EventArgs e) {
if (cmbusertype.SelectedItem == null) {
MessageBox.Show("Please select User Type to continue...");
cmbusertype.Focus();
return;
}
if (txtuserid.Text == "") {
MessageBox.Show("Please enter your UserID...");
txtuserid.Focus();
return;
}
if (txtpassword.Text == "") {
MessageBox.Show("Please enter your password...");
txtpassword.Focus();
return;
}
try {
SqlConnection con = new
SqlConnection(#"Data Source = (LocalDB)\MSSQLlocaldb; Initial Catalog = AdminAuthentication; Integrated Security = True"); ;
SqlCommand cmd = new SqlCommand("select * from SimplifyLogin where userID='" + txtuserid.Text + "' and password='" + txtpassword.Text + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
string cmbItemValue = cmbusertype.SelectedItem.ToString();
if (dt.Rows.Count > 0) {
if(dt.Rows[0]["UserType"].ToString() == cmbItemValue) {
if (cmbusertype.SelectedIndex == 0 ) {
MessageBox.Show("You are logged in as " + dt.Rows[0][2] + Environment.NewLine + "Displaying Admin Dashboard");
this.Hide();
} else {
MessageBox.Show("Welcome Student! Displaying Exam Options");
this.Hide();
}
} else {
MessageBox.Show("Invalid username and/or Password.Please try again. \nAttempts: " + attempts + "out of of 3");
txtpassword.Clear();
attempts++;
if (attempts == 4) {
MessageBox.Show("You have reached maximum login attempts. Click 'Forgot Password' below to reset it.");
btnlogin.Enabled = false;
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I figured out this morning:
Here are the changes I made:
Got rid of one of the nested ifs
if ((dt.Rows[i]["UserType"].ToString() == cmbItemValue) && (cmbusertype.SelectedIndex == 0))
adjusted the } as neccesary.

Filling textbox when autofill text box selected index changed in C# windows form

I just want to fill the other textbox when user selected an string from the autofill textbox1 i am using this code for autofill a textbox.
private void frmHistory_Load(object sender, EventArgs e)
{
try
{
string query = "select ID from Customer ";
SqlCommand cmd = new SqlCommand(query,con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
AutoCompleteStringCollection mycollection = new AutoCompleteStringCollection();
while(dr.Read())
{
mycollection.Add(dr.GetInt32(0).ToString());
}
textBox1.AutoCompleteCustomSource = mycollection;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
There is no event to for selecting the autofill. What most people do is to detect the detect whether the ENTER key is clicked. I recommend to also detect the TAB key and would handle the PreviewKeyDown event:
private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyData == Keys.Enter || e.KeyData == Keys.Tab)
{
textBox2.Text = textBox1.Text;
}
}

Refresh Datagrid When Dialog Form Closed

I have an application like this:
There's one main form (frmMasuk) with datagrid and "Add New" button
When someone clicks Add New, it shows the dialog form (Form2) to add new data.
When someone clicks "Save" on dialog form, it will be closed and
the datagrid will be refreshed
I got a problem when the dialog form closes, the datagrid must be refreshed.
This is some of my code:
frmMasuk:
public frmMasuk()
{
InitializeComponent();
SqlCommand sql = new SqlCommand("SELECT * FROM kas ORDER BY id_kas, tanggal DESC", koneksi.mykonek);
koneksi.openkonek();
SqlDataReader reader = sql.ExecuteReader();
DataTable a = new DataTable();
a.Load(reader);
koneksi.closekonek();
dgv.DataSource = a;
dgv.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
frmKasNew a = new frmKasNew();
a.ShowDialog();
}
frmKasNew:
private void simpankas()
{
koneksi.openkonek();
DateTime tgl = Convert.ToDateTime(ttanggal.Text);
SqlCommand sql = new SqlCommand("INSERT INTO kas(tanggal, jenis, jumlah, keterangan) VALUES('"+ tgl +"','"+ tjenis.Text +"','" + tjumlah.Text + "','" + tket.Text +"') ",koneksi.mykonek);
int exe = sql.ExecuteNonQuery();
if (exe == 0)
{
MessageBox.Show("Data gagal disimpan ke database", "Aplikasi KAS Usaha", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show("Data berhasil disimpan!", "Aplikasi KAS Usaha", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Dispose();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (ttanggal.Text == "" || tjenis.Text == "" || tjumlah.Text == "" || tket.Text == "")
{
MessageBox.Show("Harap melengkapi data sebelum menyimpan","Aplikasi KAS Usaha",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
simpankas();
}
// end if
}
Add an event to the a.OnClose event:
private void button3_Click(object sender, EventArgs e)
{
frmKasNew a = new frmKasNew();
a.FormClosed += FormClosed;
a.ShowDialog();
}
private void FormClosed(object sender, FormClosedEventArgs e)
{
SqlCommand sql = new SqlCommand("SELECT * FROM kas ORDER BY id_kas, tanggal DESC", koneksi.mykonek);
koneksi.openkonek();
SqlDataReader reader = sql.ExecuteReader();
DataTable a = new DataTable();
a.Load(reader);
koneksi.closekonek();
dgv.DataSource = a;
dgv.Enabled = true;
}
Have you tried showing the form with a DialogResult like
private void button3_Click(object sender, EventArgs e)
{
frmKasNew kas = new frmKasNew();
DialogResult result = kas.ShowDialog():
If (result == DialogReult.OK)
{
CurrencyManager cm = (CurrencyManager)
dgv.BindingContext[a];
cm.Refresh();
}
Then use CurrencyManager to to refresh the datagrid?

Drop-down list property [duplicate]

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.

updating the datagridview [duplicate]

This question already has an answer here:
how to update data grid view in winforms?
(1 answer)
Closed 9 years ago.
i have 2 forms and dont know how to update the datagridview, if some can simply guide me please. form1 is as follows:
public partial class frmBooking : Form
{
//instance of sqlConnection created
SqlConnection con = new SqlConnection("Data Source=....");
public frmBooking()
{
InitializeComponent();
//sets the time selecter to a time format and selects the hours and mins only in 24 hour format.
TimeOfBooking.CustomFormat = "HH:mm";
TimeOfBooking.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
//combo box get data from database and updates when new customer is added
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
NameOfCustomer.Items.Clear();
SqlCommand cm = new SqlCommand("SELECT GroupName FROM Customer ORDER BY GroupName ASC", con);
try
{
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
NameOfCustomer.Items.Add(dr["GroupName"]);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//ends here
}
//sets the facility name so its copied from the previous(facility to be booked) form into the Facility text box
public void setFacility(string new_facility)
{
Facility.Text = new_facility;
}
//sets the date so its copied from the previous(facility to be booked) form into the date text box
public void setDate(string new_date)
{
Date.Text = new_date;
}
//adding a new customer button, redirects user to the add customer page
private void btnAddCust_Click(object sender, EventArgs e)
{
frmNewCustomer newCust = new frmNewCustomer();
newCust.Show();
this.Close();
}
//cancel button will redirect the user to the main page
private void btnCancel_Click(object sender, EventArgs e)
{
Form3 frm3 = new Form3();
frm3.Show();
this.Close();
}
private void frmBooking_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
}
private void lblBookingForm_Click(object sender, EventArgs e)
{
}
private void btnConfirm_Click(object sender, EventArgs e)
{
//validation - if any of the mandotory fields are empty an error message will apear next to the text box
if (Facility.Text == "")
{
//MessageBox.Show("Please enter valid Facility, Date, Name Of Customer, Time Of Booking and Hours");
errorFacility.SetError(Facility, "Enter A Facility To Book");
}
else if (Date.Text == "")
{
errorDate.SetError(Date, "Enter A Valid Date");
}
else if (NameOfCustomer.Text == "")
{
errorCust.SetError(NameOfCustomer, "Enter A Customer To Book");
}
else if (TimeOfBooking.Text == "")
{
errorTime.SetError(TimeOfBooking, "Enter A Time To Book");
}
else if (Hours.Text == "")
{
errorHours.SetError(Hours, "Enter The Hours To Book");
}
//so if there isnt no error in the fields itll go on and add the data in to the database.
else
{
//instance of sqlConnection
SqlConnection con = new SqlConnection("Data Source=...");
//instance of sqlCommand
String query =
"INSERT INTO [Booking] values ('"
+ Facility.Text
+ "', '" + Date.Text
+ "', '" + NameOfCustomer.Text
+ "', '" + TimeOfBooking.Text
+ "', '" + Hours.Text
+ "', '" + Paid.Text
+ "', '" + Notes.Text
+ "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
//query executed correcty or not
con.Close();
MessageBox.Show("Sucessfully Booked");
Form3 mainPage = new Form3();
mainPage.Show();
this.Close();
}
}
}}
this is the form i am using to add a Booking.
The second form i have is the one with the datagridview, which i want to update when the booking is made the code for that is as follows:
public partial class frmViewBookings : Form
{
public frmViewBookings()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
Form3 mainpage = new Form3();
mainpage.Show();
this.Close();
}
private void frmViewBookings_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
}
}
}
To display data on your datagrid you would have to set it's Datasource first which you would do like this
datagridview1.Datasource = this.usersDataSet1.Booking.DefaultView
Whenever you want to refresh it you will just have to fill your tableadapter again and set your gridview's datasource to it.
(Create a seperate method to load datagridview)

Categories

Resources