I want to put the name of the user after they log in and saying (for example) "Welcome Bruce"
or "Welcome Batman" something like that. how can i get the value of a specific column and display it on a messagebox?? i'm using visualt studio c# 2008 and ms sql 2005. windows form
using (SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM tblUsers WHERE U_Name=#U_Name AND U_Pass=#U_Pass", conn);
cmd.Parameters.Add("#U_Name", SqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("#U_Pass", SqlDbType.VarChar).Value = textBox2.Text;
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
dr.Read();
int userType = Convert.ToInt32(dr["U_Type"]);
if (userType == 1)
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else if (userType == 2)
{
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();
}
}
here is my code
in my database i have a U_Name and F_Name, i want to display F_Name
You already have access to the data (assuming it's in the same row returned by the query), so just pop up another MessageBox that uses that value:
if (dr.HasRows)
{
dr.Read();
int userType = Convert.ToInt32(dr["U_Type"]);
MessageBox.Show("Welcome, " + dr["F_Name"].ToString())
if (userType == 1)
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else if (userType == 2)
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
}
you can use the below mentioned code on Login Successful.
MessageBox.Show("welcome "+textBox1.Text);
You can try:
Messagebox.Show(Context.User.Identity.Name.ToString());
You can use the split method like this if you want a part of the user's name like this,
Context.User.Identity.Name.ToString().Split('\\')[1]
Add User name into public static string.
Use it into all child forms.
static class Program
{
public static string sCurrentUserName;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
In your method:
if (dr.HasRows)
{
dr.Read();
int userType = Convert.ToInt32(dr["U_Type"]);
if (userType == 1)
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else if (userType == 2)
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
Program.sCurrentUserName = dr["F_Name"].ToString();
}
else
{
Program.sCurrentUserName = string.Empty;
//other code
}
How to use it in child Forms:
public partial class Form2: Form
{
public Form2()
{
}
private void Form2_Load(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(Program.sCurrentUserName) == false)
MessageBox.Show("Welcome " + Program.sCurrentUserName);
else
{
//do something
}
}
}
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";
}
}
}
}
I'm using this code to verify login information when a user login, which are not maximum of three users morning shift, evening shift, and manager.
I was different forms to open based on username. I mean:
MorningShift opens frmCashier
EveningShift opens frmCashier3
Manager opens frmAdmin
How can I do that?
The username is selected in a combo box then a password is entered.
private void button1_Click_1(object sender, EventArgs e)
{
string cmdText = "select Count(*) from Staff where Sname=#p1 and Spass=#p2";
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#p1", comboBox1.Text);
cmd.Parameters.AddWithValue("#p2", textBox1.Text); // Is this a variable or a textbox?
int result = (int)cmd.ExecuteScalar();
if (result > 0)
{
this.Hide();
var form1 = new frmCashier();
form1.Closed += (s, args) => this.Close();
form1.Show();
}
else
MessageBox.Show("...");
}
}
Something like below should work:
Form form1;
if (result > 0)
{
this.Hide();
if (comboBox1.Text.ToLower() == "MorningShift") {
form1 = new frmCashier();
}
else if (comboBox1.Text.ToLower() == "EveningShift") {
form1 = new frmCashier3();
}
else if (comboBox1.Text.ToLower() == "Manager") {
form1 = new frmAdmin();
}
else {
throw new Exception("unknown user");
}
form1.Closed += (s, args) => this.Close();
form1.Show();
}
I made a login page that checks the database for the username and password but it's just allowing any username and password it's not rejecting them not sure why I'm new to this, below is the form, I've entered data into the database with user_name and password so it's deffo not that must be something in the code but when I close out of the program it also says password incorrect which is strange it only shows that once I've actually clicked close on the program tho it's weird
namespace LoginApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
PassTextBox.PasswordChar = '•';
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string MyConnection = "datasource=localhost;port=3306;username=user;password=pass";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand("select * from etool.login where user_name='" + this.UserTextBox.Text + "' and password='" + this.PassTextBox.Text + "' ;", MyConn);
MySqlDataReader MyReader;
MyConn.Open();
MyReader = MyCommand.ExecuteReader();
int count = 0;
while (MyReader.Read())
{
Console.WriteLine(MyReader[count]);
count++;
}
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
if (count == 1)
{
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and passwor.\nAccess denied.");
}
else
{
MessageBox.Show("Username and password is incorrect.\nPleas try again.");
}
MyConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
First, you REALLY should use parameters instead of construct your command with the variables like you did.
Second, you shouldn't put here your user and pass for root.
Third, you will ALWAYS show the message "Username and password is correct", as nothing is preventing this from happening.
Actually, your code is like this:
while (MyReader.Read())
{
Console.WriteLine(MyReader[count]);
count++;
}
//This block of code will ALWAYS be executed,
//no matter the value of count.
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
//This IF block is doing nothing.
if (count == 1)
{
}
As you can see, the code that should be executed ONLY in case the counter had a value of 1 is executed no matter what.
You need to put the part of your code that must be executed only if count is equal to 1 INSIDE the IF that checks if count is equal to 1:
if (count == 1)
{
MessageBox.Show("Username and password is correct");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
guys
I am trying to work on a final project for the school. The task is to create a login form that will ask user id, password, check it with table and then depending on user's role (student, admin or faculty) direct it to different form. I did try answers here, but for some reason I can't get the code working.
My login page sits there with "ready" and "running" and not doing anything. Where is my mistake? Here is my code:
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
DataTable result = LoginDB.Login(txtUID.Text, txtpwd.Text);
if (result.Rows.Count == 1)
{
string role = result.Rows[0]["UserType"].ToString();
switch(role)
{
case "student":
Students form = new Students();
form.ShowDialog();
this.Hide();
break;
case "admin":
Administrators frm = new Administrators();
frm.ShowDialog();
this.Hide();
break;
case "faculty":
Faculty fom = new Faculty();
fom.ShowDialog();
this.Hide();
break;
}
}
else
{
MessageBox.Show("Invalid UserID or Password", "Invalid Login");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and LoginDB code:
public static DataTable Login(string UserID, string Password)
{
try
{
SqlConnection conn = SchoolDB.Connected();
SqlCommand cmd = new SqlCommand("Select UserType from Login where UserID=#id and Password=#pwd", conn);
cmd.Parameters.AddWithValue("#id", UserID);
cmd.Parameters.AddWithValue("#pwd", Password);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
conn.Close();
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
I would greatly appreciate any help.
how to load and unload form in C#.
so i have 2 form, login form and welcome form, so in here, i use session, if session is 1, when the login form load it's automatically closed and load welcome form.
I use this code,but it is not work,, the login form still open.
private void Login_Form_Load_1(object sender, EventArgs e)
{
string st = "1";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=GATEWAY-PC\SQLSERVER;Initial Catalog=train_system;Integrated Security=True";
SqlCommand cmd = new SqlCommand("SELECT * FROM employer WHERE session='" + st + "'",conn);
conn.Open();
SqlDataReader dr1;
dr1 = cmd.ExecuteReader();
if (dr1.Read())
{
string dr = dr1[2].ToString();
if (dr == "1")
{
Form1 fm = new Form1();
fm.Show();
Login_Form lf = new Login_Form();
lf.Close();
}
else {
}
}
else {
}
}
The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.
if (dr1.Read())
{
string dr = dr1[2].ToString();
if (dr == "1")
{
this.Close();
Form1 fm = new Form1();
fm.Show();
}
}
This line of code
Login_Form lf = new Login_Form();
lf.Close();
will create a completely new instance of the Login_Form and thus you are facing this problem
If the login form is your main form you can hide it withthis.hide(); in the welcome form load event and then you can can create a closing event on your welcome form and there you can use Application.Exit(); to shutdown everything in your application...
if (dr1.Read())
{
string dr = dr1[2].ToString();
if (dr == "1")
{
Form1 fm = new Form1();
fm.Show();
this.hide();
}
}
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}