C#中字符串列表出错

时间:2010-04-24 00:48:28

标签: c#

相同的命名空间:2个表单。

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
        }
有人帮帮我吗? :(为什么我的字符串是NULL ???????? textBox不是空的...谢谢!

3 个答案:

答案 0 :(得分:2)

button1_Click处理程序中,您创建的是本地变量UserList,而不是使用ListAcc.的静态成员

尝试更改

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

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

答案 1 :(得分:1)

你想要更像这样的东西:

    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 
    } 

答案 2 :(得分:0)

代码完全混乱。

你的问题不是文本框(因为即使它是空的,字符串也会是“”但永远不会为空)。您的问题是静态UserList永远不会被设置。

此外,编译器会警告像frmDangky.ListAcc.UserList这样的结构。它警告有一个原因,所以请至少修正警告。