C# Query : When I login to my software I select the desired username using combobox. After I login, I want to see the username text in the main window on the toolstrip.

I tried get and set method but something is going wrong. Can you please help me out? Thanks in advance.

Form 1:

public partial class login : Form
{
public login()
{
    InitializeComponent();
}

public string username
{
    get{
        return a.ToString();}
}

public string a;

private void button1_Click(object sender, EventArgs e)
{
    a = comboBox1.Text;
    Form main1 = new main();
    main1.Show();
 // rest is the code for login.
}

}

Form 2:

public partial class main : Form
{
public main()
{
    InitializeComponent();
}
public string username
{
    set { toolStripLabel1.Text = value; }
}
private void main_Load(object sender, EventArgs e)
{
    Form home = new home();
    home.MdiParent = this;
    home.WindowState = FormWindowState.Maximized;
    home.Show();
}
}

Here Home is form3 a childform which opens in Main form. at load event of Main form itself.

I would prefer that you have a static class with a static variable of type string.
A static class needs no implementation.

public static class Common
{
    public static string UserName;
}

and for calling use

Common.UserName = ComboBox1.Text;

You don't need to a static class just pass the username to the username variable

Something like this:

This would go in your login:

    private void button1_Click(object sender, EventArgs e)
    {
        a = comboBox1.Text;
        Form main1 = new main();
        mail1.username = comboBox1.SelectedItem1.ToString;
        main1.Show();
    }

This would go in you main form to put the name in the textbox:

    public main()
    {
        InitializeComponent();
        textBox1.Text = username;
    }

Hope this helps

I would change your code completely. I would run login before form1 initialization. If login is successful, then open form1, and pass the argument to it (argument from login form to form1 as parameter):

 static class Program
 {
  [STAThread]
  static void Main()
  {   
    using (Login login = new Login())
    {
     login.StartPosition = FormStartPosition.CenterScreen;
     if (login.ShowDialog() == DialogResult.OK)
     {      
      Application.Run(new Form1(login.strUserName)); //passing the userName to the constructor of form1 (see bellow)
     }
   }
  }
 }

//form1:
 public partial class Form1 : Form
 {  
  string userName;  //class variable!
  public Form1(string _strUser)
  {   
   InitializeComponent();
   userName = _userName; //a local variable of a form1 class has hold user`s name (userName - which u can call it from within the form1 class!
   //you can use this variable in some control:
   label1.Text = "Logged user: " + userName;
  }
 }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.