将单个数据片段添加到多个列表框?

时间:2012-04-18 00:13:52

标签: c# winforms

我正在为一个程序编写代码,该程序要求用户输入有关其主页的数据。他们有两个选择。他们可以输入有关他们的家或公寓的信息。他们输入有关房产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());
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在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());