将单个数据片段添加到多个列表框
本文关键字:列表 添加 单个 数据 片段 | 更新日期: 2023-09-27 18:31:23
我正在为一个程序编写代码,该程序要求用户输入有关其房屋的数据。 他们有两个选择。 他们可以输入有关其房屋或公寓的信息。 他们输入有关物业ID,地址,卧室,建造年份,价格和平方英尺的数据,并在两个单独的文本框中输入有关其是否配备的信息(这是针对公寓选项)或输入车库容量(这是用于房屋选项)。 这六个参数适用于基类,带家具或车库容量是公寓或房屋的两个子类。 当用户单击"添加公寓"或"添加房屋"按钮时,地址应进入公寓列表框或家庭列表框。 这就是我遇到障碍的地方。
private void btnAddApartment_Click(object sender, EventArgs e)
{
//instantiate appartment and add it to arraylist
try
{
Apartment anApartment = new Apartment(txtID.Text, txtAddress.Text, int.Parse(txtYearBuilt.Text), int.Parse(txtBedrooms.Text),
double.Parse(txtSquareFootage.Text), double.Parse(txtPrice.Text), txtFurnished.Text);
Home.Add(anApartment);
ClearText(this);
}
catch (Exception)
{
MessageBox.Show("Make sure you entered everything correctly!", "Error", MessageBoxButtons.OK);
}
}
private void btnAddHouse_Click(object sender, EventArgs e)
{
try
{
House aHouse=new House(txtID.Text, txtAddress.Text, int.Parse(txtYearBuilt.Text), int.Parse(txtBedrooms.Text),
double.Parse(txtSquareFootage.Text), double.Parse(txtPrice.Text),int.Parse(txtGarageCapacity.Text));
Home.Add(aHouse);
AddHouseToListBox();
ClearText(this);
}
catch (Exception)
{
MessageBox.Show("Make sure you entered everything correctly!", "Error", MessageBoxButtons.OK);
}
}
private void ClearText(Control controls)
{
foreach (Control control in controls.Controls)
{
if (control is TextBox)
{
((TextBox)control).Clear();
}
}
}
private void AddHouseToListBox()
{
lstHouse.Items.Clear();
foreach (House person in Home)
{
lstHouse.Items.Add(person.GetAddress());
}
}
private void AddApartmentToListBox()
{
lstApartment.Items.Clear();
foreach (Apartment persons in Home)
{
lstApartment.Items.Add(persons.GetAddress());
}
}
您需要
在btnAddApartment_Click中调用AddApartmentToListBox
private void btnAddApartment_Click(object sender, EventArgs e)
{
//instantiate appartment and add it to arraylist
try
{
Apartment anApartment = new Apartment(txtID.Text, txtAddress.Text, int.Parse(txtYearBuilt.Text), int.Parse(txtBedrooms.Text),
double.Parse(txtSquareFootage.Text), double.Parse(txtPrice.Text), txtFurnished.Text);
Home.Add(anApartment);
AddApartmentToListBox();
ClearText(this);
}
catch (Exception)
{
MessageBox.Show("Make sure you entered everything correctly!", "Error", MessageBoxButtons.OK);
}
}
此外,而不是每次都可以将AddApartmentToListBox
替换为
lstApartment.Items.Add(anApartment.GetAddress());
和AddHouseToListBox
lstHouse.Items.Add(aHouse.GetAddress());