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.
Related
In form 1
public void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\ALLENSQL;Initial Catalog=TITOMSLogin;Integrated Security=True");
SqlDataAdapter sdf = new SqlDataAdapter("select usertype, fullname, position from login where username= '" + txtuser.Text + "' and password='" + txtpass.Text + "'", con);
DataTable dt = new DataTable();
sdf.Fill(dt);
string fullname = dt.Rows[0]["FullName"].ToString();
string position = dt.Rows[0]["Position"].ToString();
if (dt.Rows.Count == 1)
{
this.Hide();
if (dt.Rows[0]["Usertype"].ToString() == "Admin")
{
Form2Admin ss = new Form2Admin(position + ": " + fullname);
Form3Admin sa = new Form3Admin(position + ": " + fullname);
Form5 sw = new Form5(position + ": " + fullname);
ss.Show();
sa.Hide();
sw.Hide();
}
now this code doesn't work in other forms
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form3Admin.Show();
}
this is the scenarios I am trying to achieve:
After pressing login form2 will show up, form 3 and form 4 is hidden.
button in form 2 is press (Form 2 will hide, Form 3 will show).
button in form 3 is press (Form 3 will hide, Form 4 will show).
button in form 4 is press (form 4 will hide, Form 2 will show but all data written before must still be there) and so on to the other forms.
You have to use the same actual Form3Admin instance to Show it. Keep Form3Admin sa instance as a class variable and use that instance when you want to show it.
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
sa.Show();
}
I got 2 forms (1)Login (2)User basically User types in username & password checks database if its found they are directed into (2)User I want to pass Username from form (1) to (2) so I can refer to that and display user account information in the (2) form. I've this this code but not sure if its right cause it wont display in textbox(Username) on form 2.
//Form(1)
public FormLogin()
{
InitializeComponent();
}
public string StrUsername{
get { return txtboxUser.Text; }
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Hide();
Main ss = new Main();
ss.Show();
txtboxUser.Text = String.Empty;
txtboxPass.Text = String.Empty;
}
private void btnEnter_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\Graded unit Dev\BlackMarch\BlackMarch\bin\Debug\DataBaseBM.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From UserData where Username= '" + txtboxUser.Text + "' and Password = '" + txtboxPass.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
User ss = new User();
ss.Show();
}
else
{
MessageBox.Show("Wrong Username Password");
}
}
//Form User(2)
private void btnHotelResort_Click(object sender, EventArgs e)
{
panelPicture.Visible = false;
var formlogin1 = new FormLogin();
txtUsernameUser.Text = formlogin1.StrUsername;
}
Add property in User form and set it on successful login:
public string UserName {get; set;} // In User form
Upon logon:
this.Hide();
User ss = new User();
ss.UserName = txtboxUser.Text;
ss.Show();
Then, you can access UserName inside User
txtUsernameUser.Text = UserName;
Your FormUser(2) must be :
public FormLogin frm;
public FormUser (FormLogin frm)
{
InitializeComponent();
this.frm=frm
}
private void btnHotelResort_Click(object sender, EventArgs e)
{
panelPicture.Visible = false;
txtUsernameUser.Text = frm.StrUsername;
}
In your From1 :
private void btnExit_Click(object sender, EventArgs e)
{
this.Hide();
Main ss = new Main(this);
ss.Show();
txtboxUser.Text = String.Empty;
txtboxPass.Text = String.Empty;
}
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.
I got a comboBox in FORM1 that gets the value from the database
FORM1 Code:
public void fillComboBox()
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("Select LastName, FirstName, MiddleName from EMP", myDatabaseConnection))
using (SqlDataReader sqlreader = mySqlCommand.ExecuteReader())
{
while (sqlreader.Read())
{
string Lname = sqlreader.GetString(sqlreader.GetOrdinal("LastName"));
string Fname = sqlreader.GetString(sqlreader.GetOrdinal("FirstName"));
string Mname = sqlreader.GetString(sqlreader.GetOrdinal("MiddleName"));
string fullName = Lname + ", " + Fname + " " + Mname;
comboBox3.Items.Add(fullName);
}
}
}
}
From the FORM1 I have a button that opens the FORM2 where I could add data in the database.
FORM2 Code:
public void addData()
{
string a = "INSERT INTO Emp(LastName, FirstName, MiddleName) Values('"+textBox1.Text+"', '"+textBox2.Text+"', '"+textBox3.Text+"')";
using (SqlConnection myDatabaseConnection1 = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection1.Open();
using (SqlCommand mySqlCommand = new SqlCommand(" " + a + " ", myDatabaseConnection1))
mySqlCommand.ExecuteReader();
}
}
private void button1_Click(object sender, EventArgs e)
{
addData();
Form1 nf = new Form1();
nf.fillComboBox();
this.close
}
I check the database and verified the data is added.
The problem is when I add data in the datatabase the comboBox don't update the data it loads. It only updates after I run the program again.
With this code:
Form1 nf = new Form1();
nf.fillComboBox();
You are creating a new Form1 after db update (and not showing it). You are not refreshing the original Form1.
To see this, add: nf.Show(); after the fillComboBox() call.
You have to refresh the original Form1 after closing Form2.
example:
if(form2.ShowDialog() == DialogResult.OK)
fillComboBox();
and in fillComboBox, you should clear comboBox3.Items before adding new entries.
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.