c# load and unload form - c#

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

Related

loading window application forms based on Query executed

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

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

Showing message box in form2 when i press the cancel button

I have got three forms, of a winform app. in which form3 there are two butons and some textboxes. I wanted to know why my form is showing a messagepop called "Duplicate" when I press the cancel button of the form.
I actually told the form3 to cancel and return to the form1. Its doing the job. but before coming to the form1 it's showing me a messagebox "Duplicate" which I don't want to see.
How can I avoid this popup?
Codes in form3
private void submit_Click(object sender, EventArgs e)
{
// this button click event handler will raise the
// event which can then intercepted by any listeners
//some codes....
this.Dispose();
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close();
}
Codes in form1
private void btn_open_form3_Click(object sender, EventArgs e)
{
Form3 f = new Form3();
string l = "true";
// Add an event handler to update this form
// when the address form is updated (when AddressUpdated fires).
f.AddressUpdated += new Form3.AddressUpdateHandler(AddressForm_ButtonClicked);
f.ShowDialog();
if (String.IsNullOrEmpty(file_NameTextBox.Text.ToString()))
{
frmShowMessage.Show("Try again!!!", "Missing!!!!", enumMessageIcon.Error, enumMessageButton.OK);
//cell_check();
}
else
{
if (checkexistornot())
{
if (file_NameTextBox.Text == string.Empty)
{
cell_check();
}
else
{
SqlConnection con = new SqlConnection(#"Data Source=DVSQL\SQLEXPRESS;Initial Catalog=CncDB;Persist Security Info=True;User ID=CncDbUser;Password=*****");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO cncinfo (part,drawings,draftpath,comments) VALUES ('" + file_NameTextBox.Text + "','" + drawingsTextBox.Text + "','" + gcodeTextBox.Text + "','" + commentsTextBox.Text + "') ", con);
cmd.ExecuteNonQuery();
con.Close();
load_table();
}
}
}
}
private void AddressForm_ButtonClicked(object sender, AddressUpdateEventArgs e)
{
// update the forms values from the event args
file_NameTextBox.Text = e.File_Name;
drawingsTextBox.Text = e.Drawings;
gcodeTextBox.Text = e.Gcode;
commentsTextBox.Text = e.Comments;
}
public bool checkexistornot()
{
SqlConnection con = new SqlConnection(#"Data Source=DVSQL\SQLEXPRESS;Initial Catalog=CncDB;User ID=CncDbUser;password=*****");
con.Open();
SqlCommand cmd = new SqlCommand("select part from cncinfo where part='" + this.file_NameTextBox.Text + "' ;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#part", SqlDbType.NVarChar).Value = Convert.ToString(dataGridView1.Rows[0].Cells["Part Number"].Value);
object obj = cmd.ExecuteScalar();
cmd.ExecuteNonQuery();
con.Close();
if (obj!=null)
{
frmShowMessage.Show(""Duplicate!!!!", enumMessageIcon.Warning, enumMessageButton.OK);//- - - ->>showing this line if i press the cancel_Click from FORM3
cell_check();
return false;
}
else
return true;
}
If you want your code to not execute code after clicking the cancel button in Form3, one option is taking advantage of the DialogResult property.
Cancel button click handler:
private void cancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
Imediately after showing Form3 ("f.ShowDialog();")
if (f.DialogResult == DialogResult.Cancel)
{
return;
}
Hope it helps.

How to display the user's name on a messagebox in c#?

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
}
}
}

Refresh datagridview1 on form1 each time form2 is closed

How do I refresh datagridview1 on form1 each time form2 is closed?
i.e. refreshDataGridView1() needs to be run, but I'm not too sure how to go about initializing it.
What needs to go in refreshDataGridView1()?
private void save_btn_Click(object sender, EventArgs e)
{
if (pgpText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: PGP");
}
else if (teamText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: Team");
}
else
{
using (OleDbConnection conn = new OleDbConnection())
{
string pgp_new = pgpText.Text;
string pgp_old = pgpOld.Text;
string team = teamText.Text;
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='db.mdb'";
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText = "UPDATE PGP SET PGP=?,Team=? WHERE PGP=?";
command.Parameters.Add("pgp_new", OleDbType.VarChar).Value = pgp_new;
command.Parameters.Add("team", OleDbType.VarChar).Value = team;
command.Parameters.Add("pgp_old", OleDbType.VarChar).Value = pgp_old;
conn.Open();
int affectedRows = (int)command.ExecuteNonQuery();
if (affectedRows == 0)
{
command.CommandText = "INSERT INTO PGP (PGP,Team) VALUES (?, ?)";
command.Parameters.RemoveAt(2);
command.ExecuteNonQuery();
if (MessageBox.Show("Table Saved!", "Update", MessageBoxButtons.OK) == DialogResult.OK)
{
//refreshDataGridView1();
this.Close();
}
}
if (affectedRows > 0)
{
if (MessageBox.Show("Table Saved!", "Update", MessageBoxButtons.OK) == DialogResult.OK)
{
//refreshDataGridView1();
this.Close();
}
}
}
}
}
use OnFormClosing event of your Form2 and in that event call your method refreshDataGridView1()
EDIT:
In your refreshDataGridView1() method just rebind the grid like
private void refreshDataGridView1()
{
GridView1.DataSource = <some data Source>;
}
I suggest you to make a function in Form1 and call it upon exiting in Form2 (Form_Closing). I mean when Form2 is closing, call the function. The function should update your datagridview.
How can you access the function? Well, you can easily pass this to Form2 while creating:
Form2 frm2 = new Form2(this);
And in your Form2:
private Form1 frm1;
public Form2(Form1 frm1)
{
this.frm1 = frm1;
}
private void Form2_Form_Closing(...)
{
this.frm1.UpdateDataGridViewFunc();
}
Treat your Form2 as a Dialog. Move your MessageBox and UpdateDatagridview logic in Form1. Whenever you have finished your query (in Form2), pass DialogResult.OK. It will also close your form.
Form2:
if (affectedRows > 0)
{
//ok some rows were affected, close the form and pass OK result
this.DialogResult = DialogResult.OK;
}
Back in Form1:
private void openForm2()
{
var f2 = new Form2(); //create new form2
var formResult = f2.ShowDialog(); //open as Dialog and check result after close event
if (formResult == DialogResult.OK) //check form2 dialog result
{
//form2 gave OK, I can update my DGV and display msg
MessageBox.Show("DGV will be updated", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
//update my DGV
UpdateDGV();
}
else
{
//form2 passed Cancel or something else, not good
MessageBox.Show("Form2 Closed but nothing happened.", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void UpdateDGV() {
//refresh datagridview1 datasource
}
Assign the Form2_FormClosed event:
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form2_FormClosed);
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
refreshDataGridView1();
}
DataGridView.DataSource = dataset; // get new result set
Something like this should go in refreshDataGridView1()
For accessing Form1 elements in Form2 add a public property in Form1.
public DataGridView DataGridView1
{
return dataGrid; // this should be your data grid id
}
In form2, you can access form1 as
Form1 form1 = new Form1();
form1.DataGridView1.DataSource = dataSource;
If one form contains another you can create a constructor to pass one to another.
private Form1 form1;
public Form2(Form1 form1)
{
this.form1 = form1;
}

Categories

Resources