error with string list in C#
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!
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>();
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
}
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.
精彩评论