Enabling a button from another form and closing the form - c#

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.

Related

C# I can't print variable text in other Form

I trying to code program and I have two forms (Form1 is for loging and Form2 is empty for now, but I would like to print Logged: 'Name' + 'Surename' from DB).
I created class User which has Name and Surename (both public static strings) and method GetUserInfo() to get Name and Surename by user's Login. If I print User.Name + User.Surename in MsgBox after program checks login and password everything is ok, but after Form2 loads then
label1.Text = "User: " + User.name + " " + User.surename;
in method public Form2() shows just User: and nothing more.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string login = textBox1.Text;
string pass = textBox2.Text;
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2015\Projects\*\*\Database1.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand query = new SqlCommand("Select * from Users where login='" + login + "' AND password ='" + pass + "'", connection);
connection.Open();
SqlDataReader Reader = query.ExecuteReader();
int count = 0;
Form1 form1 = new Form1();
Form2 form2 = new Form2();
while (Reader.Read())
{
count += 1;
}
if (count == 1)
{
this.Hide();
form2.Show();
User.GetUserInfo(login);
MessageBox.Show(User.name + " " + User.surename);
}
else
MessageBox.Show("Bad Login");
}
}
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
label1.Text = "User: " + User.name + " " + User.surename;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label1_Click_1(object sender, EventArgs e)
{
}
}
and User class:
public class User
{
public static string name { get; set; }
public static string surename { get; set; }
public static void GetUserInfo(string login)
{
using (SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2015\Projects\*\*\Database1.mdf;Integrated Security=True;Connect Timeout=30"))
using (SqlCommand query = new SqlCommand("Select FirstName, LastName from Users where login='" + login + "'", connection))
{
connection.Open();
SqlDataReader Reader = query.ExecuteReader();
while (Reader.Read())
{
User.name = Reader["FirstName"].ToString();
User.surename = Reader["LastName"].ToString();
}
}
}
}
Thank you!
Use this code:
User.GetUserInfo(login);
this.Hide();
Form2 form2 = new Form2();
form2.Show();
because you need first set values for name and surename and then use it.
In your case, you first show Form2 and then set values
Add public variables or properties to Form1 so that you can access them:
in Form1:
public User user;
....
user.name = Textbox1.Text;
user.surname = Textbox2.Text;
In your Form2:
Form frm = new Form1();
frm.ShowDialog();
label1.Text = "User: " + frm.user.name + " " + frm.user.surename;
frm.Dispose();
So the problem you have is that you are creating Form2 before the properties in the User class are filled.
This is why :
label1.Text = "User: " + User.name + " " + User.surename;
This is called inside the constructor of Form2. This means whenever you initialize this form with
Form2 form2 = new Form2();
all code in the constructor executes.
So the label text will be set when creating the form.
User.GetUserInfo(login); is called after this, the data will be empty for Form2 since the form is already created.
A possible solution would be
To set the label in the form2 loading event and call User.GetUserInfo(login); before form2.Show();
or
Calling Form2 form2 = new Form2(); after User.GetUserInfo(login);
You are setting the label text in the constructor of Form2. At that point they don't have a value as you haven't read the data from the database yet, so the label will simply read:
User:
It won't change until you update it's value again. You need to call a method on Form2 to update the label text once the call to User.GetUserInfo has completed successfully.
if (count == 1)
{
this.Hide();
form2.Show();
User.GetUserInfo(login);
// Update the label text here
MessageBox.Show(User.name + " " + User.surename);
or swap the order of getting the user information and constructing Form2:
if (count == 1)
{
this.Hide();
User.GetUserInfo(login);
form2 = new Form2();
form2.Show();
Either way will work, the one you choose depends on what else you need to do with your forms.

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

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.

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

Loging in in loginform and see it to in form2

Ok i got a form called Form2, this is the form where you should see every thing and update everything out of a phpmyadmin database.
Then a second form that calls loginFrm, thats activated from Form2.
The only code i need or solution is if you login onto the loginform it should keep the status en can be called from the FORM2 if the login is TRUE or FALSE.
loginFrm.cs code:
private void connectBtn_Click(object sender, EventArgs e)
{
MySqlConnection sconn = new MySqlConnection("User ID=root;Password=;Initial Catalog=cmstt;Data Source=localhost");
sconn.Open();
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter("select * from users where email ='" + UsrName.Text + "' and pass='" + PassWrd.Text + "'", sconn);
da.Fill(ds);
int count = ds.Tables[0].Rows.Count;
if (count == 0)
{
MessageBox.Show("Invalid UserID/Password");
}
else
{
this.Visible = false;
MessageBox.Show("gelukt");
}
sconn.Close();
}
If you give me help would you want to be clear about where i have put which code?
Thanks
Well in your Form2 which brings up the loginFrm, you could prompt like this:
if (loginFrm.ShowDialog() == Windows.Forms.DialogResult.OK)
{
//Only move on if logged in succeeded
MessageBox.Show("gelukt");
DoOtherStuff();
}
else
{
MessageBox.Show("Invalid UserID/Password");
}
In your login form:
if (count == 0)
{
this.DialogResult = Windows.Forms.DialogResult.Cancel;
}
else
{
this.DialogResult = Windows.Forms.DialogResult.OK;
}

Categories

Resources