【发布时间】:2019-07-26 19:22:11
【问题描述】:
我正在制作一个 Windows 窗体,用户可以在其中建立多个联系人(存储在列表框中的对象中),当单击一个项目时,文本框将显示联系人信息。但是,无论我点击多少次,我的文本框都只保存一个列表框项目信息。
我试着做一个foreach循环,但还是不行
public partial class FormManager : Form
{
FormContact contactForm;
Contact contact;
public FormManager()
{
InitializeComponent();
ControlsDisabled();
}
private void btnAdd_Click(object sender, EventArgs e)
{
contactForm = new FormContact();
if (contactForm.ShowDialog() == DialogResult.OK)
{
//I think this is the main problem the ig
txtFname.Text = contactForm.firstname;
txtLname.Text = contactForm.lastname;
contact = contactForm.contact;
lstBoxAdd.Items.Add(contact.firstname + " " + contact.lastName);
ControlsEnabled();
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
contactForm.Show();
contactForm.Visible = false;
if (contactForm.ShowDialog() == DialogResult.OK)
{
txtFname.Text = contactForm.firstname;
txtLname.Text = contactForm.lastname;
contact = contactForm.contact;
lstBoxAdd.Items.Add(contact.firstname + " " + contact.lastName);
ControlsEnabled();`enter code here`
}
}
private void lstBoxAdd_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstBoxAdd.SelectedIndex != -1)
{
Contact selectedcontact = (Contact)lstBoxAdd.SelectedItem;
txtFname.Text = selectedcontact.firstname;
txtLname.Text = selectedcontact.lastName;
}
}
//The other form where the textboxes are getting updated from
public string firstname;
public string lastname;
public Contact contact;
public FormContact()
{
InitializeComponent();
}
public FormContact(Contact contact)
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
contact = new Contact(txtFname.Text, txtLname.Text);
firstname = txtFname.Text;
lastname = txtLname.Text;
this.Hide();
}
//the class of the contact objects
public class Contact
{
public string firstname;
public string lastName;
public Contact()
{
}
public Contact(string FirstName, string LastName)
{
firstname = FirstName;
lastName = LastName;
}
}
【问题讨论】:
-
这里有很多问题。您只声明了一个
Contact contact;类对象。您需要一个List<Contact>,它必须是您的列表框的数据源。添加新联系人时,请将其添加到List<Contact>,不要将字符串添加到列表框。FormContact用作对话框。单击btnSave时,关闭它,不要隐藏它。btnSave.DialogResult的属性必须设置为OK(请参阅设计器)。删除contactForm.Show();和contactForm.Visible = false;。当您编辑一个项目时,您需要将该项目(一个联系人对象)apss 到FormContact。其他一些问题。 -
您可以使用标准的 DataBindings 来简化整个过程。查看
BindingSource和BindingList类。