0

Same namespace: 2 forms.

public class Account       //frm1
        {
            public string Username;
            public string Password;

        }

        public class ListAcc
        {
            public static List<Account> UserList;
        }

 private void button1_Click(object sender, EventArgs e)
        {

            List<Account> UserList = new List<Account>();
            Account acc = new Account();
            acc.Username = textBox1.Text;
            acc.Password = textBox2.Text;
            UserList.Add(acc);
        }

 private void button2_Click(object sender, EventArgs e)  //frm2
        {
            string p = frmDangky.ListAcc.UserList[0].Username; // null ->error
            string p = frmDangky.ListAcc.UserList[0].Password; // null ->error
        }

Someone help me? :( why my string is NULL???????? The textBox is not empty... Thanks!

3 Answers 3

2

In the button1_Click handler, you're creating a local variable UserList, instead of using the static member of ListAcc.

Try changing

List<Account> UserList = new List<Account>();

to

ListAcc.UserList = new List<Account>();
Sign up to request clarification or add additional context in comments.

Comments

1

You want something more like this:

    public class ListAcc 
    { 
        public static List<Account> UserList = new List<Account>();
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
        Account acc = new Account(); 
        acc.Username = textBox1.Text; 
        acc.Password = textBox2.Text; 
        ListAcc.UserList.Add(acc); 
    } 

    private void button2_Click(object sender, EventArgs e)  //frm2 
    { 
        string p1 = ListAcc.UserList[0].Username; // null ->error 
        string p2 = ListAcc.UserList[0].Password; // null ->error 
    } 

Comments

0

The code is a complete mess.

And your problem is not the textbox (because even if it would be empty the string would be "" but never null). Your problem is that the static UserList never gets set.

Moreover the compiler does warn about constructs like frmDangky.ListAcc.UserList. It warns for a reason, so please at least fix the warnings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.