0

I have two forms in the same namespace.

One is the main form that displays the list of accounts.

public partial class Server : Form
{

    public Server()
    {
        InitializeComponent();
        LoadAcounts();
    }

    public void LoadAcounts()
    {
        AccountDB acc = new AccountDB();
        userListBox.DataSource = acc.ListUsers();

        this.userListBox.SelectedIndex = 0;
    }
}

Second is the registration form.

public partial class RegForm : Form
{
    public RegForm()
    {
        InitializeComponent();

        passBox.Text = "";
        passBox.PasswordChar = '*';
        passBox.MaxLength = 14;
        passBox2.Text = "";
        passBox2.PasswordChar = '*';
        passBox2.MaxLength = 14;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (passBox.TextLength >= 4 && passBox.Text == passBox2.Text && usernameBox.TextLength >= 4)
        {
            AccountDB acc = new AccountDB();
            if (acc.UserExist(usernameBox.Text))
            {
                MessageBox.Show("User already exists!");
            }
            else
            {
                string user = usernameBox.Text;
                string pw = PasswordHash.HashPassword(passBox.Text);

                WriteDB(user, pw);
                this.Close();
                MessageBox.Show("Registration successful!");
                //LoadAccounts();
            }
        }
    }
}

I am currently stuck on how can I call LoadAccounts() after Registration successful so the userListBox will be refreshed to include the newly added account.

marneee
  • 25
  • 1
  • 3

2 Answers2

0

I am not sure about your design, but you can create an instance property of the "Server" class in your "RegForm" class. BUT, I should say that is increasing class coupling and definitely is not a good pattern.

public partial class RegForm : Form
{
    public Server serverFormInstance {get; set;}//must be filled from caller code
...
...
0

If you have only one instance of the Server form, you can make it as a singleton to be able to call the method.

public class Server : Form
{
  static internal readonly Server Instance = new Server ();

  private Server()
  {
    InitializeComponent();
    LoadAcounts();
  }
}

Or any singleton implementation you like.

So you'll change all access to Server by Server.Instance.

Now you can call:

Server.Instance.LoadAcounts();

But if you plan to allow several instances of Server, a registration method may be used but it requires more code of your project to think about that.

You can also read this:

Communicate between two windows forms in C#