为了让您的代码真正可重用,您应该严格区分显示(视图)和数据。
你没有提到你有一个数据库。这种不提的是这种分离的开始。如果您只有一个帐户列表或一个字典,或者一个包含要在应用程序中编辑的项目的文本文件,您的问题就会类似。
因此,让我们假设您想要编辑Accounts
的集合。您希望能够将帐户添加到此集合中,或者更改此集合中现有帐户的数据。
该功能类似于ICollection<Account>
的功能。
所以Form1
需要知道的是,它是否拥有ICollection<Account>
。不知何故,在初始化期间Form1
加载Accounts集合。如果操作员按下添加,则会打开一个Form2
,他可以填写新帐户所需的值。操作员选择OK
或Cancel
来表示他希望将该帐户添加到收藏中(使用窗体中的保存按钮不是Windows标准,并且有点不清楚,因此不要使用它)。
在Form2
添加帐户
守则Form1
private ICollection<Account> existingAccounts;
void OnButtonAdd(object sender, ...)
{
using (var form = new Form2())
{
form. ...// fill any needed values
// show form2 and check if OK or Cancel:
var dlgResult = form.ShowDialog(this);
// only add if OK pressed, otherwise ignore
if (dlgResult == DialogResult.OK)
{
this.existingAccounts.Add(form.Account);
}
}
}
电导率在Visual Studio设计创建形式为ID的文本框和一个文本框输入密码(给它密码属性,所以它显示*****)
添加一个OK和一个取消按钮。为这些按钮的DialogResult属性提供适当的OK和Cancel值。
最后补充一个属性来获取类型的值:
public Account Account
{
get
{ // extract the values from the display
return new Account()
{
Id = this.TextBoxId.Text,
Pwd = this.TextBoxPwd.Text,
};
}
}
编辑现有帐户
你也有一个按钮,编辑现有帐户。你只想修改最近添加的帐户,还是希望能够编辑任何现有帐户?
在后一种情况下,您必须做出显示所有现有帐户的信息,操作员可以在其中选择其中一个帐户。可能使用DataGridView或BindingSource。您最终可能会得到如下功能:
Account GetSelectedAccount() {...}
编辑现有帐户的表单与创建新帐户的表单类似。你应该真的考虑使用相同的形式。
public Account Account
{
get
{ // extract the values from the display
return new Account()
{
Id = this.TextBoxId.Text,
Pwd = this.TextBoxPwd.Text,
};
}
set
{
this.TextBoxId.Text = value.Id;
this.TextBoxPwd.Text = value.Pwd;
}
}
在Form1,当按下编辑:
void OnButtonEdit_Click(object sender, ...)
{
using (var form = new FormEdit())
{
Account accountToEdit = this.GetSelectedAccount();
form.Account = accountToEdit;
// or: GetLastAddedAccount if you only want to edit the last added one
var dlgResult = form.ShowDialog(this);
if (dlgResult == DialogResult.OK)
{ // extract the edited Account from the form:
Account editedData = form.Account;
this.UpdateSelectedAccount(editedData);
}
}
}
就像在上面的例子中我通常决定具有与插入和提取的帐户而不是访问每单独帐户属性的属性的接口。这允许您更改帐户的内部,而不必改变所有(软件)的用户此帐户的
请分享到目前为止,你已经尝试的代码。@乔纳森Niixtay –
对于您必须使用数据库将存储值即用户名和密码。 – Pirate
而且...请详细解释您的实际问题在哪里。 –