Share an instance of a object between windows technique - c#

I have a wpf application with a MainWindow and the user click a login button that open a new window i created. in that new window.cs file i have the user type in username which is stored in a new instance of the user class. I want to have that username (stored in the new instance of the class) accessible in the MainWindow.cs
whats the best practice for this?

You can always expose that through a public property on the login form, much like with OpenFileDialog :
void Login()
{
var login = new LoginForm();
if (login.ShowDialog() == DialogResult.OK)
{
var userName = login.UserName;
}
}
public class LoginForm : Form
{
public string UserName { get; private set; }
public void OnOKButton_Click(object sender, EventArgs e)
{
// validation...
this.DialogResult = DialogResult.OK;
this.UserName = UserNameTextBox.Text;
this.Dispose();
}
}

Related

Toggle and communicate between two Windows forms in Visual C#?

I have two forms in my Windows Form Application, a main and a login info form.
The main form has a button which opens the login info form on being clicked. The login info form gets displayed as a new form on the main window with the main window also being visible in background while the user enters login info. If the login info is correct the login form should close while the main form should display the string "Welcome" and the correct username from login form. Now the issue is that after entering the correct login info on the login form and clicking the Login button, a new window of the main form appears with the previous main form also running as shown in the figure..
How can I make the previous instance of main form close and get the correct text displayed? Any help is appreciated.
I am using the following codes for creating and opening the main and the login info forms.
Code snippet of main form:
public partial class Main_Form : Form
{
private string u_name = "";
public Main_Form(string username)
{
InitializeComponent();
u_name = username;
label1.Text = label1.Text + " " + u_name;
}
private void Loginbutton_Click(object sender, EventArgs e)
{
Form Form2 = new login_Form();
Form2.ShowDialog();
}
}
Code snippet of login form:
public partial class login_Form : Form
{
public static string username = "";
public login_Form()
{
InitializeComponent();
}
private void Button_Login_Click(object sender, EventArgs e)
{
if (textBox_Login.Text == "Admin" && textBox_Password.Text == "123")
{
this.Hide();
username = textBox_Login.Text;
Form Form1 = new Main_Form(username);
Form1.ShowDialog();
}
else
{
MessageBox.Show("Please Enter Username and/or Password Again!");
}
}
}
You shouldn't have 2 instances of MainForm, just use one and update as required.
In your mainform you should call the LoginForm and check the DialogResult (I will explain this later).
So here, if you get an OK result it means the Login worked, otherwise the user cancelled.
So in MainForm change the constructor to be empty and remove the u_name parameter
public Main_Form()
{
....
}
private void Loginbutton_Click(object sender, EventArgs e)
{
Form Form2 = new login_Form();
if(Form2.ShowDialog() == DialogResult.OK) //We call LoginForm and wait for a Result
{
//Login was successful. Then we can set the label to the username, which is now a property for Login Form (see below)
label1.Text = Form2.UserName;
}
else
{
//Login was cancelled
//You must now implement logic to handle this case
}
}
Now in the Login form you want to check login and return the dialog result to the MainForm. DialogResult is, as the name suggests, the result of calling the LoginForm Dialog.
You will also need another click event for the cancel button.
public partial class login_Form : Form
{
//username is changed to a property
public string Username { get; private set; }
public login_Form()
{
InitializeComponent();
}
private void Button_Login_Click(object sender, EventArgs e)
{
//The check remains as before.
if (textBox_Login.Text == "Admin" && textBox_Password.Text == "123")
{
//If successful, we set the dialogresult, username and close this form.
this.Username = textBox_Login.Text;
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
//Otherwise we handle the error
MessageBox.Show("Please Enter Username and/or Password Again!");
}
}
//The new click event for the cancel button
private void Button_Login_Cancel(object sender, EventArgs e)
{
//We set the dialogresult to cancel (could be anything else) and close
this.DialogResult = DialogResult.Cancel;
this.Close();
}
}

How to return values, entered by the user in a welcome screen, to the main screen after closed? [duplicate]

This question already has answers here:
Send values from one form to another form
(20 answers)
Closed 2 years ago.
Previous Post
As per my previous post. I got it working correctly.
In the welcome screen, the user enters his/her details. Like name and surname. Then the user clicks the next button. The welcome screen closes and the main window opens.
However, the name and surname are no longer accessible in the main.cs file.
The welcome screen code:
public string username;
public string usersurname;
static private Form Sender;
static public void Run(Form sender)
{
if (sender == null)
throw new ArgumentNullException();
Sender = sender;
new WelcomeForm().ShowDialog();
}
public WelcomeForm()
{
InitializeComponent();
}
private void sign_in_Click(object sender, EventArgs e)
{
username = textBox1.Text;
usersurname = textBox2.Text;
Close();
}
My Main window code:
private void Form1_Load(object sender, EventArgs e)
{
WelcomeForm.Run(this);
}
public Form1()
{
InitializeComponent();
}
How do I get access to username and usersurname in my main.cs file as well?
Updated Code (Welcome screen):
private WelcomeFormInputData InputData = new WelcomeFormInputData();
static private Form Sender;
static public WelcomeFormInputData Run(Form sender)
{
if (sender == null)
throw new ArgumentNullException();
Sender = sender;
var form = new WelcomeForm();
return form.ShowDialog() == DialogResult.OK ? form.InputData : null;
}
private void ButtonValidate_Click(object sender, EventArgs e)
{
InputData.UserName = textBox1.Text;
InputData.UserSurname = textBox2.Text;
DialogResult = DialogResult.OK;
Close();
}
public WelcomeForm()
{
InitializeComponent();
}
public class WelcomeFormInputData
{
public string UserName { get; set; }
public string UserSurname { get; set; }
}
You can simply improve the Run method as:
static public WelcomeForm Run(Form sender)
{
if (sender == null)
throw new ArgumentNullException();
Sender = sender;
var form = new WelcomeForm();
return form.ShowDialog() == DialogResult.OK ? form : null;
}
You need to manage this dialog result with a button :
private void ButtonValidate_Click(object sender, EventArgs e)
{
UserName = textBox1.Text;
UserSurname = textBox2.Text;
DialogResult = DialogResult.OK;
Close();
}
Every form has some properties to manage that:
https://learn.microsoft.com/dotnet/api/system.windows.forms.form.dialogresult
By default, the result is DialogResult.None when a form is closed.
A non-null result indicates the user had validated something and the opener form can use results as you done by assigning public fields that you should set to external read only properties:
public string UserName { get; private set; }
public string UserSurname { get; private set; }
Another mean is to return a structured data entity instead of the form itself:
public class WelcomeFormInputData
{
public string UserName { get; set; }
public string UserSurname { get; set; }
}
So you can change that in the welcome form:
private WelcomeFormInputData InputData = new WelcomeFormInputData();
static public WelcomeFormInputData Run(Form sender)
{
if (sender == null)
throw new ArgumentNullException();
Sender = sender;
var form = new WelcomeForm();
return form.ShowDialog() == DialogResult.OK ? form.InputData : null;
}
private void ButtonValidate_Click(object sender, EventArgs e)
{
InputData.UserName = textBox1.Text;
InputData.UserSurname = textBox2.Text;
DialogResult = DialogResult.OK;
Close();
}
Here we return only the data if validated.
You can name artifacts as you need to be the most meaningful, the simplest and the most coherent.
Note: you can change Form by MainForm if you need to control the MainForm specializations.
static public WelcomeForm Run(MainForm sender)
But perhaps you can throw out the Sender usage because in the main form you call Run and next you can show it and use the inputed data:
static public WelcomeFormInputData Run()
{
var form = new WelcomeForm();
return form.ShowDialog() == DialogResult.OK ? form.InputData : null;
}
And from the main form:
var userdata = WelcomeForm.Run();
Show();
if ( userdata != null )
{
... userdata.UserName ...
... userdata.UserSurname ...
}
You can use like WelcomeForm.username and you can create class called LocalVar to access and store any data from any form e.g.
in `LocalVar` class use this type of variables:
`public static string username = "";`
`public static string usersurname = "";`
After this before you close WelcomeForm do code like this:
private void sign_in_Click(object sender, EventArgs e)
{
LocalVar.username = textBox1.Text;
LocalVar.usersurname = textBox2.Text;
Close();
}
and now you can usr `LocalVar.username` anywhere in project.

How can I pass a variable across windows so that it can be used in every window or just make it visible to my entire program?

My program is a fitness tracker. I can get the user logged in but once that happens need to pass the users information across windows so that their username(their unique identifier) can be used to track information properly in their file.
login window code
public partial class UserLoginWindow : Window
{
public UserLoginWindow()
{
InitializeComponent();
}
private void LogIn_Click(object sender, RoutedEventArgs e)
{
//loads users from file into a list we can use to search for individual user information
DataManagement loadUserList = new DataManagement();
List<User> Users = loadUserList.ReadUsers();
string username = Convert.ToString(userUsername.Text);
string password = Convert.ToString(userPassword.Text);
//checks to see if the username and password match a saved profile and allows access to
//profile window if the user login is valid
User user = new User();
bool allowLogin = user.UserLogIn(username, password, Users);
if (allowLogin == true)
{
//returns the user we are using to here so that we know
//what user we need to personalize the profile for
PatientProfileWindow patientWindow = new PatientProfileWindow(username, Users);
patientWindow.Show();
this.Close();
}
else
{
MessageBox.Show("LogIn Failed. Please Try Again");
userUsername.Clear();
userPassword.Clear();
}
}
private void CreateNewAccount_Click(object sender, RoutedEventArgs e)
{
//opens window for user to create new profile
CreateNewProfileWindow createProfile = new CreateNewProfileWindow();
createProfile.Show();
this.Close();
}
}
profile window(one of the windows i want to pass the logged in users information to)
public partial class PatientProfileWindow : Window
{
public PatientProfileWindow(string username, List<User> Users)
{
InitializeComponent();
User user = new User();
User currentUser = user.GetLoggedInUser(username, Users);
userDoctorName.Content = currentUser.Doctor; //add this once making changes to exclude doctors
userName.Content = currentUser.Name;
userWeight.Content = currentUser.Weight;
userHeight.Content = currentUser.Height;
}
private void logOut_Click(object sender, RoutedEventArgs e)
{
UserLoginWindow login = new UserLoginWindow();
login.Show();
this.Close();
}
private void trackActivity_Click(object sender, RoutedEventArgs e)
{
TrackActivityWindow activityWindow = new TrackActivityWindow();
activityWindow.Show();
this.Close();
}
private void trackNutritionalIntake_Click(object sender, RoutedEventArgs e)
{
TrackNutritionalIntakeWindow intakeWindow = new TrackNutritionalIntakeWindow();
intakeWindow.Show();
this.Hide();
}
private void button_Click(object sender, RoutedEventArgs e)
{
EditProfileWindow editProfile = new EditProfileWindow();
editProfile.Show();
this.Hide();
}
}
There are many ways to skin this cat. Some better then others.
Simple Static Utility Class
public static class Utils
{
public static string Username{get;set;}
}
You can use this class from any of your forms to set or get the data.
DI Container
Another approach is to use a DI container. I'm not sure about how to wire up a DI container, but you could pass in the dependencies you need
IPrincipal
You can set the current principal on the thread:
System.Threading.Thread.CurrentPrincipal=new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity("josh"),null)
There are many ways to do this. What you are looking for is a good old static class.
create some class
public static class MySharedData {
public static string UserID ="";
}
and the you can use in your code
MyShaderData.UserID = "123" or whatever. Notice this class does not need (nor should in this case) be instantiated)

Passing values through forms c#

I am building a form application at Visual Studio 2015 in C#. First of all i've made a user login form using 2 textboxes and 1 button. All i want to do is to pass the value from the textbox that contains username to a label which is located to another form which form is called MainMenu. This is my code for the button i made to the login form:
private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
MainMenu ss = new MainMenu();
ss.Show();
}
and the code for the MainMenu form that i want to pass the value is the following:
private string value1 = string.Empty;
public string Value1
{
set { value1 = value; }
get { return value1; }
}
private void MainMenu_Load(object sender, EventArgs e)
{
label7.Text = Value1;
}
As you can see i have create a property in MainMenu form that is accessible from login form so i could transfer the value from textbox1 directly in your MainMenu form. The problem is that the text in label7 remains empty during runtime and i can't understand why. Am i missing something from my code or i am doing something completely wrong ?
Any suggestions would be appreciated
You actually create two Forms: username and ss. You set Value1 of username, but you show ss which you didn't set its Value1. So you should show username:
private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
username.Show(); // and not ss.Show();
}
Also, a tip, use better names for your variables. The code below do exactly the same thing but is much more comprehensible:
private void loginButton_Click(object sender, EventArgs e)
{
var mainMenuForm = new MainMenu();
mainMenuForm.UserName = userNameTextBox.Text;
this.Hide();
mainMenuForm.Show();
}
class MainMenu : Form
{
// This is an "Auto-Implemented Property".
// Auto-Implemented Properties are used as a shortcut of what you have done.
// Google them for more information.
public string UserName { get; set; }
private void MainMenu_Load(object sender, EventArgs e)
{
userNameLabel.Text = UserName;
}
}
MainMenu username and MainMenu ss are two distinct instances (of the same MainMenu class, but that's a detail).
You are setting the memeber variable Value1 of username instance but you are displaying ss instance.
Consider this code
private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
usename.Show();
}
You are using two different MainMenu objects, the right code should be something like
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
username .Show();
Just as a completely different approach to the problem:
Another option is to create a static class in your project that will house any variables that you would like to reuse.
So lets say your static class is call Globals, after successfull login you would set the variable you require ie Globals.Username = textBox1.Text.
Then wherever you need that value again you can access it using Globals.Username.
When you need to pass variable values from one form to another, write the constructor of the second form accordingly and pass the value while creating the object of the second form.
private void button_login(object sender, EventArgs e)
{
MainMenu ss= new MainMenu(textBox1.Text);
this.Hide();
ss.Show();
}
class MainMenu : Form
{
// This is an "Auto-Implemented Property".
// Auto-Implemented Properties are used as a shortcut of what you have done.
// Google them for more information.
public string UserName { get; set; }
private void MainMenu(string userName)
{
this.UserName = userName;
}
}
Creating public properties and accessing them in another class for every instance of the class is bad practice for OOP.

closing password form c#

How can I close the password form when my new form opens?
public partial class Password : Form
{
private string password;
public Password()
{
InitializeComponent();
}
private void pass_TextChanged(object sender, EventArgs e)
{
password = "1234";
}
private void okButton_Click(object sender, EventArgs e)
{
if (passtextBox.Text == password)
{
list form = new list();
form.Show();
}
else
{
MessageBox.Show("Incorrect Password. Try Again!!");
}
}
}
When I use this.close(); my new form and password form both close.
What should I do?
I assume your PasswordForm is the main form for you which you passsed inside Application.Run method.
So when the main form closes application will exit.
I'd suggest you to just hide the form instead of closing it.
list form = new list();
form.Show();
this.Hide();
You can use MDI form as the parent form.
When a new form is created and that new form(which is a child form of the MDI form) is opened over the MDI or any parent form, then you can search for all the opened child form. If any child form is found open, then close that child form. In this way you can manage form opening and closing.
Thanks.
You want to show new form and close first form if password is correct, don't you?
Try this:
Form secondform = new form();
Secondform.show();
Form1 firstform = new form1();
Firstform.hide();
i fixed it myself
public partial class Password : Form
{
private string password;
public Password()
{
InitializeComponent();
}
private void pass_TextChanged(object sender, EventArgs e)
{
password = "1234";
}
private void okButton_Click(object sender, EventArgs e)
{
if (passtextBox.Text == password)
{
// list form = new list();
//form.Show();
//list secondform = new list();
//secondform.Show();
//Password firstform = new Password();
// firstform.Hide();
this.Hide();
list sistema = new list();
sistema.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Incorrect Password. Try Again!!");
}
}
}
}

Categories