I am trying to emulate a button click when the enter key is pressed in a text box. I have used this before too but it just doesn't seem to work now.
Please check the code I am using below and let me know if I missed something. I have been away from coding for almost a year now maybe I am missing something?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
String uname, password, query;
int counter = 0;
public Form1()
{
InitializeComponent();
}
private void login_Click(object sender, EventArgs e)
{
verify();
}
private void pass_KeyDown(Object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
verify();
}
}
private void verify()
{
uname = name.Text; //Initialize variables
password = pass.Text;
uname = uname.Trim(); //Sanitize input
password = password.Trim();
query = "SELECT * FROM login WHERE uname = #uname AND pass = #pass";
string conString = Properties.Settings.Default.libConnectionString;
using (SqlCeConnection conn = new SqlCeConnection(conString))
{
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand(query, conn))
{
cmd.Parameters.AddWithValue("#uname", uname);
cmd.Parameters.AddWithValue("#pass", password);
cmd.ExecuteNonQuery();
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
counter = 1;
Variables.username = reader["uname"].ToString();
Variables.passw = reader["pass"].ToString();
if (reader["regid"].ToString() != null)
{
Variables.regid = reader["regid"].ToString();
}
MessageBox.Show(Variables.username + ", you are now logged in!");
}
if (counter == 0)
{
MessageBox.Show("Invalid details");
}
}
}
}
}
}
I am coding in C# in the IDE Visual Studio 2012
Whenever you create a method with the intention to handle an event, you need to make sure you register the method as a handler to the desired event. If you are not doing so the program will not guess that your method was meant to be an event handler.
try this :
if (args.KeyCode == Keys.Return)
{
login_Click.PerformClick();
}
Related
I want to check ManagerUsername and ManagerEmail in the database and the display a messagebox to show the user with their password.But when I execute the code it shows me that:
"commandtext has not been initialized"
so I want to know how can I fix my code to display what I want. And also a way to improve my code to work more efficient
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Cybertronics
{
public partial class passwordRecovery : Form
{
int pin = 0;
private int _failedAttempts = 0;
public passwordRecovery()
{
InitializeComponent();
}
private void passwordRecovery_Load(object sender, EventArgs e)
{
lblAttempt.Visible = false;
}
private void btnBackLogin_Click(object sender, EventArgs e)
{
loginFrm loginForm = new loginFrm();
this.Hide();
loginForm.Show();
}
private void btnSubmitEmail_Click(object sender, EventArgs e)
{
try
{
string emailAddress = txtEmail.Text;
string username = txtManagerUsername.Text;
string password = "ChangeMe";
CyberDatabase db = new CyberDatabase();
db.OpenConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Parameters.AddWithValue("#ManagerUsername", username);
cmd.Parameters.AddWithValue("#ManagerEmail", emailAddress);
db.SetSqlCommand(cmd);
reader = db.Select();
cmd.CommandText = "SELECT ManagerUsername from tblManagers WHERE ManagerUsername = #ManagerUsername and ManagerEmail = #ManagerEmail";
db.SetSqlCommand(cmd);
reader = db.Select();
if (reader.HasRows)
{
reader.Read();
SqlCommand passwordUpdate = new SqlCommand();
passwordUpdate.CommandText = "UPDATE tblManagers SET ManagerPassword=#Password WHERE ManagerUsername=#ManagerUsername and ManagerEmail=#ManagerEmail";
db.SetSqlCommand(passwordUpdate);
MessageBox.Show("your new password is:" + password);
}
else
{
if (pin != 21)
{
_failedAttempts++;
MessageBox.Show("Wrong password or username fail to login. you have" + (3 - _failedAttempts) + " attempts more.", "EPIC FAIL", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
if (_failedAttempts == 3)
{
Application.Exit();
}
}
}
}
catch (SqlException sql)
{
CyberMethods.DisplayErrorMessage(sql.Message);//error message from cybermethods class for DB
}
catch (Exception exc)
{
CyberMethods.DisplayErrorMessage(exc.Message);//error message from cybermethods class
}
}
}
}
your code is very messy and untidy. It is very error prone. Check the below sample code for best practices.
using (connection)
using (SqlCommand command = new SqlCommand(
"SELECT ManagerUsername from tblManagers WHERE ManagerUsername = #ManagerUsername and ManagerEmail = #ManagerEmail",
connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
}
}
you have multiple query statements. for the seperation of duties principles I suggest you to make 3 functions each seperate and call them respectively.
and It is wise to keep connection open then then close when all the operations finish.
For solving your error
before your first db.SetSqlCommand(cmd); just add your query statement with
cmd.CommandText = "select ....." ;
I'm building a desktop application where when a used logged it in new his Id will be appeared in textBox. But in my case query run successfully but id doesn't appear in textBox..can anyone help me to find it out please?
First form of User logged in (Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
public string employeeID;
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True");
connection.Open();
String query = "select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
string employeeID = myReader["EmployeeID"].ToString();
}
myReader.Close();
SqlDataAdapter sda = new SqlDataAdapter(query,connection);
connection.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
}
}
}
Second form (Entry.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class Entry : Form
{
public Entry()
{
InitializeComponent();
}
public Entry(string employeeId)
{
InitializeComponent();
idTextBox.Text = employeeId;
}
private void reportButton_Click(object sender, EventArgs e)
{
Report report = new Report();
report.Show();
}
}
}
Remove local variable declaration, because employeeID is a global variable and already declared first, so when you prefix it using string its create another local variable which is not accessible outside this scope
while (myReader.Read())
{
employeeID = myReader["EmployeeID"].ToString();
}
You have a local variable. You can correct and optimize you code like this:
private void loginButton_Click(object sender, EventArgs e)
{
//If use set quote into your textbox
string name = nameTextBox.Text.Replace("'", "''");
string pass = passwordTextBox.Text.Replace("'", "''");
String query = string.Format("select * from Employees where Name = '{0}' and Password = '{1}'", name, pass);
string employeeID = "";
using (SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True"))
{
connection.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(query, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
employeeID = dt.Rows[0]["EmployeeID"].ToString();
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
dt.Dispose();
}
}
}
I`ve made a login form with access db, which I only need the password from.
The connection to db is successful, but when I press the button, the messagebox shows me "incorrect password", even if I insert a correct one from my db.
here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace TAC_receptie
{
public partial class login : Form
{
OleDbConnection connection = new OleDbConnection();
public login()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:login1.accdb;Persist Security Info=False;";
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText="select * from user1 where Password =' " +txtPassword.Text+ " '";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count++;
}
if (count == 1)
{
date_personale Form = new date_personale();
Form.Show();
}
else
{
if (count > 1)
{
MessageBox.Show("duplicat!!!");
}
if (count < 1)
{
MessageBox.Show("parola incorecta!!!");
}
}
connection.Close();
}
private void login_Load(object sender, EventArgs e)
{
try
{
connection.Open();
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error"+ ex);
}
}
private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
btnLogin.PerformClick();
}
}
}
remove unnecessary space from
Password =' " +txtPassword.Text+ " '"
to
Password ='" +txtPassword.Text.Trim()+ "'"
I am working with C# (visual studio 2012 professional) and Mysql . I trying to create a login form, where a user needs to insert the username and password:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Dark_Heresy
{
public partial class Login_Menu : Form
{
private MySqlConnection connection = new MySqlConnection();
public Login_Menu()
{
InitializeComponent();
TextPassword.PasswordChar = '*';
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_Login_Click(object sender, EventArgs e)
{
try
{
string connectionString = "datasource = localhost; port = 3306; username = root; password = Mypass;";
using(MySqlConnection myConn = new MySqlConnection(connectionString))
using(MySqlCommand selectCommand = new MySqlCommand())
{
selectCommand.CommandText = ("SELECT COUNT(1) FROM dark_heresy.users WHERE users_=#User and password_=#Password;");
selectCommand.Connection = myConn;
selectCommand.Parameters.Add(new MySqlParameter("User", MySqlDbType.VarChar).Value = TextUserName.Text);
selectCommand.Parameters.Add(new MySqlParameter("Password", MySqlDbType.VarChar).Value = TextPassword.Text);
myConn.Open();
var ret = selectCommand.ExecuteScalar();
var count = Convert.ToInt32(ret);
if (count == 1)
{
this.Hide();
Menu mn = new Menu();
mn.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Duplication of Username and Password... Access Denied");
}
else
{
MessageBox.Show("Incorrect Username and/or Password");
}
}
}
catch (Exception exp)
{
MessageBox.Show("Error: \r\n" + exp);
}
}
}
}
I don't get any syntax errors, but when i run this code i recieve this error:
MySql.Data.MySqlClient.MySqlException(0x80004005):
Only MySqlParameter objects may be stored at MySql.Data.MySqlClient.MySqlParameterCollection.Add(Object value)
at Dark_Heresy.Login_Menu.btn_Login_Click(Object sender, EventArgs e)
I know for security reason is it a better idea to use mysql.user table instead of dark_heresy.users table for user check, but right now is for testing purpose.
What is wrong with the code?
it says there is an error in line 39
I think your parameter syntax is wrong.
= operator returns the right side value also instead of just assigning. That's why;
new MySqlParameter("User", MySqlDbType.VarChar).Value = TextUserName.Text;
expression returns TextUserName.Text as a value and your parameter part will be like;
selectCommand.Parameters.Add(TextUserName.Text);
The right syntax seems;
selectCommand.Parameters.Add("#User", MySqlDbType.VarChar).Value = TextUserName.Text;
selectCommand.Parameters.Add("#Password", MySqlDbType.VarChar).Value = TextPassword.Text;
And please, don't store your passwords as a plain text.
Read: Best way to store password in database
My page does not redirect to the Page I have specified. While I am doing so it says The name "Response" does not exist in the current context
Please also help me with getting the register value in the database while doing the signup.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace LoginSystem123
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, EventArgs e)
{
var myConnection = new SqlConnection();
myConnection.ConnectionString = #"Data Source=mukesh-PC\SQLEXPRESS;Initial Catalog=testDb;Integrated Security=True;Pooling=False";
var myCommand = new SqlCommand();
var cmd = "SELECT * FROM [User] Where [User].Email =" + "'" + textBoxEmail.Text + "'";
myCommand.CommandText = cmd;
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
myConnection.Open();
var myReader = myCommand.ExecuteReader();
bool isRegisteredUser = myReader.Read();
if (isRegisteredUser)
{
var PasswordFromDatabase = myReader.GetString(5);
if (textBoxPassword.Text == PasswordFromDatabase.TrimEnd())
{
MessageBox.Show("Successfully Logged on !");
}
else
{
MessageBox.Show("Invalid password. Try again");
}
}
else
{
MessageBox.Show("Invalid user");
}
}
/* private void buttonSignUp_Click(object sender, EventArgs e)
{
Response.Redirect("SignUp.cs");
}
*/
private void buttonSignUp_Click_1(object sender, EventArgs e)
{
Response.Redirect("SignUp.cs");
}
}
}
Response.Redirect is used to redirect to another page in an ASP website - nothing like this works in Windows Forms.
If SignUp.cs defines a Form, you can do something like this to show it:
var signup = new SignUp();
signup.ShowDialog();
If you let us know more about what you're trying to do, we can probably be a bit more helpful.
Response.Redirect only works for web applications, and it looks like you're coding for Windows application.
You should do this instead:
SignUp su = new SignUp();
su.Show();
this.Hide();