2010-04-24 81 views
0

相同的命名空间:2种形式。错误C#中的字符串列表#

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 ????????文本框是不是空的...谢谢!

回答

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

button1_Click处理程序中,你要创建一个本地变量UserList,而不是使用静态的ListAcc.

构件尝试改变

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

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

代码中,我一个完整的混乱。

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

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