loading window application forms based on Query executed - c#

I have a two form Loginform and Setupform. if user is yet to setup the necessary parameter login form should be hide on Application.Run(new login()); and Application.Run(new Details()) should show
private void countmem1()
{
sqlconnect conss = new sqlconnect();
conss.Connections();
SqlCommand gold = new SqlCommand("select Address, Name from Detail where USER_name='admin'", conss.con);
SqlDataReader srd = gold.ExecuteReader();
if (srd.Read())
{
this.Show();
}
else
{
this.Close();
DETAILS f2 = new DETAILS();
f2.Show();
//MessageBox.Show("USER DOESN'T EXIST");
}
}

Related

check login credentials and open form based on username C#

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();
}

search user id in database and display user name in second form c#

I have a table with the columns Name, UserID, Password, UserType.
Also I have a login form where the user types userID/password combination, selects userstype (student or instructor) and clicks the button OK. If such combination of id/password exists the program opens a new form - student or instructor form depending on selected user type. What I want to do is, when the second form opens the label on the form to indicate: Logged in: "Name". I know that if I put the code in the form1
if(rbtnStud.checked)
{
Students form = new Students (txtUID.Text);
formShowDialog;
this.Hide();
}
and in the second form
public Students(string txtBox)
{
InitializeComponent();
lblName.Text = txtBox;
}
this will display UserID in the label. But I want Name from the table to be displayed, not UserID. Is it possible?
Thank you.
OK, here is the additional information: I am using WinForms
Code to pull out information from database in "LoginDB" class:
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;
and on main form:
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
DataTable result = LoginDB.Login(txtUID.Text, txtpwd.Text);
if (result.Rows.Count == 1)
{
if (rbtnStud.Checked)
{
Students form = new Students(txtUID.Text);
form.ShowDialog();
this.Hide();
}
else if{}
Change the SqlCommand to return the Name instead of the UserType:
SqlCommand cmd = new SqlCommand("Select Name from Login where UserID=#id and Password=#pwd", conn);
Update the click event on the main form:
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
DataTable result = LoginDB.Login(txtUID.Text, txtpwd.Text);
if (result.Rows.Count == 1)
{
if (rbtnStud.Checked)
{
// pass the name to the students form
Students form = new Students(dt.Rows[0]["Name"] as string);
form.ShowDialog();
this.Hide();
}
else if{}
....

c# load and unload form

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();
}

C# loading the main form after successful login

I have two forms namely Login and Main Form. I want that on successful log in, the log in page should close and the main form should load. But the problem that I was facing was whenever I enter invalid username and password, the main form still shows up.
I am accepting login message(Login Successfull Or Failed) as a string from SQL Server 2008 database
I tried using the following codes
Code:
public Form1()
{
FrmLogin frm = new FrmLogin();
frm.ShowDialog();
InitializeComponent();
}
Code:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FrmLogin frm = new FrmLogin();
if (frm.ShowDialog() == DialogResult.OK)
{
Application.Run(new Form1());
}
else
{
Application.Exit();
}
}
Login Form Button Code:
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("File Name=E:\\Vivek\\License Manager\\License Manager\\login.udl");
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("checkuser",conn);
cmd.CommandType = CommandType.StoredProcedure;
OleDbParameter p1=new OleDbParameter("userid",username.Text);
OleDbParameter p2 = new OleDbParameter("password",password.Text);
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
var returnParameter = cmd.Parameters.Add("#ReturnVal",OleDbType.VarChar,50);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
// Retrieve the return value
string result = returnParameter.Value.ToString();
MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
Stored Procedure
ALTER proc [dbo].[usercheck]
(#userid varchar(20),
#password varchar(20))
as
begin
if exists(select userid,password from users where userid=#userid and password=#password)
return 0
else
return 1
end
But unfortunately none of the above codes seem to work. I found the above code snippets from questions asked by others here but they are not working for me.
Can anyone help me to rectify this?
Thanks
This is because you are doing it wrong,
1.) This is the Constructor for the Form1 and this code is executed whenever the form is created, so you are displaying your FrmLogin form as soon as you show your Form1.
public Form1()
{
FrmLogin frm = new FrmLogin();
frm.ShowDialog();
InitializeComponent();
}
2.) This is the Entry Method for your Windows Form Application, this gets executed when you press F5 to run your Project, Here you are creating FrmLogin and just checking if the user pressed OK then display Form1. This is the right track but you are probably not checking any credentials...
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FrmLogin frm = new FrmLogin();
if (frm.ShowDialog() == DialogResult.OK)
{
Application.Run(new Form1());
}
else
{
Application.Exit();
}
Try this:
Your Program.cs:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LogonForm form = new LogonForm();
if (form.ShowDialog() != DialogResult.OK)
{
//Handle authentication failures as necessary, for example:
Application.Exit();
}
else
{
Application.Run(new Form2());
}
}
Your LogonForm:
private void Login()
{
if (CheckCredentials())
{
this.DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("Please enter correct credentials and try again!");
}
}
private void BtnLogin_Click(object sender, EventArgs e)
{
Login();
}
Edit:
If you are using SQL Server 2008 then you should use System.Data.SqlClient not System.Data.OleDb.
Here is the updated code:
private bool CheckCredentials()
{
bool result = false;
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("usercheck", conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userid", username.Text);
cmd.Parameters.Add("#password", username.Text);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
result = reader.GetBoolean(0);
}
}
}
return result;
}

Enabling a button from another form and closing the form

I have Form1 and Form2
Form1 I have a button that is disabled, but if I click on the menustrip on Form1 I go to Form2. On Form2 I log into a database. After I logged in successfully, I want Form2 to close and I want the button on Form1 to be enabled.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"...");
SqlCommand command = new SqlCommand("SELECT * FROM UserT WHERE UserName ='" +
textBox1.Text + "' AND password ='" +
textBox2.Text + "'",
connection);
connection.Open();
SqlDataReader reader = null;
reader = command.ExecuteReader();
if (reader.Read())
{
MessageBox.Show("Welcome " + reader["UserName"].ToString());
Form1 lfm = new Form1();
lfm.button1.Enabled = true;
Form2 fm = new Form2();
fm.Close();
}
else
{
MessageBox.Show("Username and password " +
textBox1.Text + "does not exist");
}
}
Open your second form using ShowDialog, then use the DialogResult returned by the ShowDialog Function to enable the Button in your first form when you close the second form
You are creating new instance of the Form1. Don't do that, instead you need to show the Form2 as dialog and set the dialog result as OK.
Like this
Form1 -
Button1_Click()
{
Form2 frm2 = new Form2();
if(frm2.ShowDialog() == DialogResult.OK)
{
button1.Enabled = true;
}
}
or
button1.Enabled = form2.ShowDialog() == DialogResult.OK;
And in the Form2, after successful login set the DialogResult as OK.
if(reader.Read())
{
DialogResult = DialogResult.OK;
Close(); //It may not required.
}
You should not create another anstances of Form1 and Form2. Instead, you shoud have a public property of Form1, so you can enable your button. like shown in the code below :
//Form 2
public Form1 MyMainForm {get; set;}
private void button1_Click(object sender, EventArgs e)
{
//Your code ...
if (reader.Read())
{
MessageBox.Show("Welcome " + reader["UserName"].ToString());
MyMainForm.button1.Enabled = true;
//If you are already id Form2
this.Close();
}
else
{
MessageBox.Show("Username and password " +
textBox1.Text + "does not exist");
}
}
And you set this MyMainForm when calling the Form2 from Form1. Like this :
Form2 f = new Form2() {MyMainForm = this};
PS : The access modifier of you button shoud be public.

Categories

Resources