How to display the logged user in listbox c# - c#

So i have a login system and when the user logins a new form opens and i want the form to display the user Name. When user register he have to put his name and surname and that 2 things i want to be displayed in the new form that opens. So is there any easy way to put the logined user name into listbox?
so here is the registration code:
MySqlConnection dataConnection = new MySqlConnection();
dataConnection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
dataConnection.Open();
MySqlTransaction transakcija = dataConnection.BeginTransaction();
MySqlCommand dataCommand = new MySqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.Transaction = transakcija;
try
{
dataCommand.CommandText = "Insert INTO login.users (ime,upIme,geslo,dovoljenja) VALUES ('" + this.tB_Ime.Text + "','" + this.tB_upIme.Text + "','" + this.tB_geslo.Text + "', 'Navaden uporabnik')";
dataCommand.CommandType = CommandType.Text;
dataCommand.ExecuteNonQuery();
transakcija.Commit();
MessageBox.Show("Registracija uspešna!");
this.Hide();
}
catch (Exception eks)
{
transakcija.Rollback();
MessageBox.Show("Napaka pri registraciji\n" + eks.Message);
}
finally
{
dataCommand.Connection.Close();
}
Form1 f1 = new Form1();
f1.ShowDialog();
this.Close();
and login:
try
{
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(" select * from login.users where upIme='" + this.tB_upIme.Text + "' AND geslo='" + this.tB_geslo.Text + "' ;", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
bool IsAdminUser = false;
while (myReader.Read())
{
count = count + 1;
IsAdminUser = myReader["dovoljenja"].Equals("Admin");
}
if (count == 1 && IsAdminUser == true)
{
MessageBox.Show("Prijavljeni ste kot administrator!");
this.Hide();
Form4 f4 = new Form4();
f4.ShowDialog();
}
else if (count == 1)
{
MessageBox.Show("Uspešno ste se prijavili!");
this.Hide();
Form3 f3 = new Form3();
f3.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Dvojno uporabniško ime in geslo!");
this.Hide();
}
else
MessageBox.Show("Uporabniško ime ali geslo ni pravilno!");
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

you can send the LoggedIn UserName to the UserForm constructor and from there you can add it to the required control.
Try This:
Login Form:
string LoggedInUserName = String.Empty;
while (myReader.Read())
{
count = count + 1;
IsAdminUser = myReader["dovoljenja"].Equals("Admin");
LoggedInUserName = myReader["FirstName"].ToString()+
myReader["LastName"].ToString();
}
if (count == 1 && IsAdminUser == true)
{
MessageBox.Show("Prijavljeni ste kot administrator!");
this.Hide();
Form4 f4 = new Form4(LoggedInUserName);
f4.ShowDialog();
}
else if (count == 1)
{
MessageBox.Show("Uspešno ste se prijavili!");
this.Hide();
Form3 f3 = new Form3(LoggedInUserName);
f3.ShowDialog();
}
Now change the both admin form(Form4) and UserForm (Form3)
//now change the Admin Form Form4 constructor to take 1 argument
public Form4(string username)
{
InitializeComponent();
myListBox.Items.Add(username);//Label1.Text= username;
}
//now change the UserForm Form3 constructor to take 1 argument
public Form3(string username)
{
InitializeComponent();
myListBox.Items.Add(username);//Label1.Text= username;
}

Related

System.ArgumentException: Data Source cannot be empty

I am not a programer, I just have a passion for this. I am doing a project which can facilitate my work, but I am facing the error described when connecting to the DB. Here is the code:
public partial class Form1 : Form
{
string dbcon = "#Data Source= KMS.db;Version=3;";
private void button1_Click(object sender, EventArgs e)
{
SQLiteConnection sqlcon = new SQLiteConnection(dbcon);
if ((textusername.Text == "") && (textpassword.Text == "") || (textusername.Text == "") || (textpassword.Text == ""))
{
EmptyErrorLabel.Visible = true;
EmptyErrorLabel.Text = "Username and / or password are empty!";
}
else
{
try
{
sqlcon.Open();
string query = "SELECT * FROM user WHERE Username = '" + textusername.Text + "' AND Password = '" + textpassword.Text + "'";
SQLiteCommand com = new SQLiteCommand(query, sqlcon);
com.ExecuteNonQuery();
SQLiteDataReader dr = com.ExecuteReader();
int i = 0;
while (dr.Read())
{
i++;
}
if(i == 1)
{
KMS_MainMenu MainMenu = new KMS_MainMenu();
MainMenu.Show();
this.Hide();
}
if(i < 1)
{
EmptyErrorLabel.Visible = true;
EmptyErrorLabel.Text = "Invalid Username and / or Password";
textpassword.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show("Error while logging: " + ex);
}
}
}

ExecuteScalar return wrong value

Good day
I am working on login page where the user will be able to login and then change password after first login.Then, the user will be able to login to the system with the new password.
I found out that ExecuteScalar will help me to make the codes working perfectly. But, I am facing now that ExecuteScalar is returning wrong values where the user will be able to change the password but it will not allow him to redirect to the main page.
I have tried to change in if statement but still it showing me wrong results
SqlConnection con = new SqlConnection(#"Data Source=TOWELL\XPEDEON;User ID=xplive;Password=xplive");
try {
con.Open();
if (attemp < 3)
{
DataTable dt = new DataTable();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = ("select count (*) from log_sup where ENTITY_DIVISION_CODE = '" + textBox1.Text + "'and DX_NUMBER = '" + textBox2.Text + "' ");
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
Form3 F3 = new Form3();
F3.Show();
this.Hide();
}
else if(result == 0)
{
recby = textBox1.Text;
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
else
{
MessageBox.Show("WRONG PASSWORD, THIS IS YOUR " + attemp + " ATTEMPT ");
}
}
else if (attemp == 3)
{
MessageBox.Show("LOGIN EXCEED , PLEASE CONTACT THE ADMIN TO RESET YOUR ACCOUNT LOGIN");
textBox1.Enabled = false;
textBox2.Enabled = false;
label2.Enabled = false;
}
attemp++;
}
catch (Exception) {
}
con.Close();
the table query
where the user after changing the password, it will marks as 1 in order to check that the password has changed
I suggest changing the query:
Count(*) can be expensive (you may want to scan the entire table), when all you want is an answer for "if there any record such that..." - you can well stop early.
Let's parametrize the query (just imagine that I put "123'; delete from log_sup; --" into textBox1.Text)
Code:
...
cmd.CommandText =
#"select 1
from log_sup
where ENTITY_DIVISION_CODE = #prm_ENTITY_DIVISION_CODE
and DX_NUMBER = #prm_DX_NUMBER";
//TODO: cmd.Parameters.Add("param_name", RDMBS_TYPE) is a better choice
cmd.Parameters.AddWithValue("#prm_ENTITY_DIVISION_CODE", textBox1.Text);
cmd.Parameters.AddWithValue("#prm_DX_NUMBER", textBox2.Text);
using (var reader = cmd.ExecuteReader()) {
if (reader.Read()) { // We've succeeded in reading (at least) one record
Form3 F3 = new Form3();
F3.Show();
this.Hide();
}
else { // the cursor is empty
recby = textBox1.Text;
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
}
...

to hide a column in grid-view for "Stockcontroller" and make it visible for "Administrator"

This is my grideview code:
I need to use a if statment for this code: private const string select_query
need to show the first code to the Administrator and the second code to the stockcontroller. i am trying to hide only one column the last "UserID".
i dont know how to call that and sign to different users using a if statement.
just tried it out!!!
this is my stock grid-view code:
SqlCommand selectCommand = new SqlCommand(" Select * from New_User where User_Name=#USER_ID", conn);
selectCommand.Parameters.Add(new SqlParameter("USER_ID", txtusername.Text.ToString());
string UserType = null;
SqlDataReader reader = selectCommand.ExecuteReader();
bool rowfound = reader.HasRows;
if (rowfound)
{
while (reader.Read())
{
UserType = reader["User_Type"].ToString().Trim();
if (UserType == "Administrator")
{
GlobalVariablesClass.VariableOne = txtusername.Text;
private const string select_query = "SELECT TOP 3 id,stock_type,stock_no,no_of_pieces,Gem_Type,Weight,Image,Cost,Create_Date,Update_Date,UserID FROM Stock_Gems";
}
else if (UserType == "StockController")
{
GlobalVariablesClass.VariableOne = txtusername.Text;
private const string select_query = "SELECT TOP 3 id,stock_type,stock_no,no_of_pieces,Gem_Type,Weight,Image,Cost,Create_Date,Update_Date FROM Stock_Gems";
}
}
}
This is my login code:
private void tbnlogin_Click(object sender, EventArgs e)
{
try
{
SqlCommand selectCommand = new SqlCommand(" Select * from New_User where User_Name=#USER_ID and Password=#PASS", conn);
selectCommand.Parameters.Add(new SqlParameter("USER_ID", txtusername.Text.ToString()));
String password = "";
using (SHA1 sha1 = SHA1.Create())
{
byte[] data = sha1.ComputeHash(Encoding.UTF8.GetBytes(txtpassword.Text));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; ++i)
{
sb.Append(data[i].ToString("x2"));
}
password = sb.ToString();
}
selectCommand.Parameters.Add(new SqlParameter("PASS", password));
string UserType = null;
SqlDataReader reader = selectCommand.ExecuteReader();
bool rowfound = reader.HasRows;
if (rowfound)
{
while (reader.Read())
{
UserType = reader["User_Type"].ToString().Trim();
if (UserType == "Administrator")
{
GlobalVariablesClass.VariableOne = txtusername.Text;
MessageBox.Show("Welcome ", "Admin Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
Admin_Menu frm = new Admin_Menu();
frm.bunifuFlatButton3.Visible = true;
frm.Show();
this.Hide();
}
else if (UserType == "StockController")
{
GlobalVariablesClass.VariableOne = txtusername.Text;
MessageBox.Show("Welcome ", "User Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
Admin_Menu frm = new Admin_Menu();
frm.bunifuFlatButton3.Visible = false;
frm.Show();
this.Hide();
}
}
}
else
{
MessageBox.Show(" Invalid User Or Password ", "Login ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
reader.Close();
}
}
I have a grid-view with columns of items as follows:
ID|Stock_Type|Stock_No|No_of_pieces|Gem_Type|Weight|Image|Cost|Create_Date|Update_date|UserID|
I found this but I don't know how retrieve from database.
This was coded into the stock gridview loader
DisplayData();
hello.Text = GlobalVariablesClass.VariableOne;
if (Roles.IsUserInRole("Administrator"))
{
this.dataGridView1.Columns[10].Visible = true;
}
else
{
this.dataGridView1.Columns[10].Visible = false;
}
**I have used the global variation which means the username who logged in will be on all the pages..

How to login with 2 user types

try
{
if (!(ComboBoxut.Text == string.Empty))
{
if (!(ComboBoxut.Text == string.Empty))
{
String str = "server=RAVI;database=sampledb;Integrated Security=SSPI";
String query = "select * from DentalLogin where usertype = '" + this.ComboBoxut.Text + "'and password = '" + this.TextBoxPwd.Text + "'";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dbr;
con.Open();
dbr = cmd.ExecuteReader();
while (dbr.Read())
{
string ut = dbr.GetString(0);
if (ut == "Doctor")
{
this.Visible = false;
DoctorHome Dochome = new DoctorHome();
Dochome.Show();
}
else if (ut == "Staff")
{
this.Visible = false;
StaffHome staffhome = new StaffHome();
staffhome.Show();
}
else
{
MessageBox.Show(" username and password incorrect", "login page");
}
}
}
Can you please tell me whats wrong with this code with a drop down button.
I have 2 user types in my form one is doctor another one is staff.
If the user selected doctor i want to show a doctorhome Form.
If the user selected staff i want to show a staffhome Form.
I got error username and pwd incorrect.
But in db everything is correct username & pwd.
Please help me out this problem.
Try This
dbr = cmd.ExecuteReader();
while(dbr.read())
{
string value = dbr["Column Index"].toString();
if(value == "Doctor" ){
this.Visible = false;
DoctorHome Dochome = new DoctorHome();
Dochome.Show();
}
}

Login authentication depending on role winforms

I have datatable like this.
uid m_code pass roleID
1 F2 F2 2
2 S2 S2 0
And i want to let user log-in depending on their roles.
I tried using this code, but it isn't working at all. Any help much appreciated.
string user = textBox1.Text;
string pass = textBox2.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from login where m_code='" + user + "' and pass='" + pass + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if(dt.Columns[3].ToString() == "0")
{
this.Hide();
StudentUI s = new StudentUI();
s.Show();
}
if (dt.Columns[3].ToString() == "1")
{
this.Hide();
TeacherUI t = new TeacherUI();
t.Show();
}
if (dt.Columns[3].ToString() == "2")
{
FacultyUI f = new FacultyUI();
f.Show();
}
else
{
MessageBox.Show("Login Failed");
}
I agree with Blachshma, you should use parameters to mitigate the risk of Sql Injections. In the meantime, let's fix up your logic:
if(dt.Rows.Count == 0)
{
MessageBox.Show("Login Failed");
return;
}
string val = Convert.ToString(dt.Rows[0][3]);
if(val == "0")
{
this.Hide();
StudentUI s = new StudentUI();
s.Show();
}
else if (val == "1")
{
this.Hide();
TeacherUI t = new TeacherUI();
t.Show();
}
else if (val == "2")
{
FacultyUI f = new FacultyUI();
f.Show();
}
else
{
MessageBox.Show("Login Failed");
}

Categories

Resources