我希望用户创建帐户,该帐户将存储在“注册”表单中的数组列表中,而“登录”表单具有一个包含所有用户名的组合框,以便用户可以选择其用户名,键入密码并继续。
我在cmb_user1.Items.Add(username);
上收到一个错误,其中用户名在当前上下文中不存在。
班级:
public class User
{
public string fname;
public string lname;
public string username;
public string password;
public string Fname
{
get { return fname; }
set { fname = value; }
}
public string Lname
{
get { return lname; }
set {lname = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public User() { }
public User (string fname, string lname, string username, string password)
{
this.fname = fname;
this.lname = lname;
this.username = username;
this.password = password;
}
}
注册表格:
public partial class sign_up_form : Form
{
ArrayList allUsers = new ArrayList();
public sign_up_form()
{
InitializeComponent();
}
private void btn_create_Click(object sender, EventArgs e)
{
try
{
if (txt_password.Text == txt_confirm_password.Text)
{
allUsers.Add(new User(txt_fname.Text, txt_lname.Text, txt_username.Text, txt_password.Text));
log_in_form login= new log_in_form(this, allUsers);
login.Show();
this.Hide();
}
}
catch
{
MessageBox.Show("Something went wrong!");
}
}
}
登录表单:
public partial class log_in_form : Form
{
sign_up_form formParent;
ArrayList allUsers;
public log_in_form(sign_up_form par, ArrayList _allUsers)
{
InitializeComponent();
this.formParent = par;
this.allUsers = _allUsers;
cmb_user1.DataSource = allUsers;
cmb_user1.Items.Add(username);
}
private void btn_signup_Click(object sender, EventArgs e)
{
sign_up_form signup = new sign_up_form();
signup.Show();
}
}
}
答案 0 :(得分:0)
您为什么需要username
?用户名已存在于您的数组列表中,但是如果您确实需要它,请尝试以下操作:
if (txt_password.Text == txt_confirm_password.Text)
{
allUsers.Add(new User(txt_fname.Text, txt_lname.Text,
txt_username.Text, txt_password.Text));
log_in_form login= new log_in_form(this, allUsers,createdUser);
login.Show();
this.Hide();
}
public log_in_form(sign_up_form par, ArrayList _allUsers,Users newUser)
{
InitializeComponent();
this.formParent = par;
this.allUsers = _allUsers;
cmb_user1.DataSource = allUsers;
cmb_user1.Items.Add(newUser);
}
或者如果您需要用户名在arraylist中,请尝试:
foreach(var item in allUsers)
{
cmb_user1.Items.Add(item.username);
}