提前感谢您的帮助!
一些背景基本上我正在构建一个存储车辆(汽车,卡车,公共汽车)的应用程序,我有一个车辆超类,所有个别类(car.cs,truck.cs,minibus.cs)都继承了这个超级。
我还有一个名为'fleet'的课程,我想将车辆添加到一个然后在列表框中显示结果。
我还有其他所有工作但我无法让卡车和小巴更新并显示在列表框上,就像汽车一样。
这是我的车队类,其中包括car.cs;它工作正常,从汽车表格中获取的数据被添加并显示在列表框中。
class Fleet
{
private List<Vehicle> theFleet = new List<Vehicle>();
public List<Vehicle> fleet
{
get
{
return theFleet;
}
}
public void deleteFromFleet(Vehicle aCar)
{
theFleet.Remove(aCar);
}
public void addToFleet(Vehicle aCar)
{
theFleet.Add(aCar);
}
}
这是我的主要表单,上面有列表框:
public partial class FrmHireCo : Form
{
private Fleet myFleet = new Fleet();
private ClientList mycustomer = new ClientList();
//Fleet object used to store cars
public FrmHireCo()
{
//Default constructor
InitializeComponent();
}
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Car c in myFleet.fleet)
{
string line = "Car: " + c.make+" " + c.colour;
lstFleet.Items.Add(line);
}
}
private void updateClientList()
{
customers.Items.Clear();
foreach (Customer c in mycustomer.clientlist)
{
string line = "Customer: " + c.name + " " + c.address;
customers.Items.Add(line);
}
}
private void btnAddCar_Click(object sender, EventArgs e)
{
//Add a new car
FrmCar carGui = new FrmCar(); //Form used to add new car
carGui.ShowDialog();
Car myCar = carGui.car; //Get new car from form
myFleet.addToFleet(myCar); //Add to fleet list
updateFleetList(); //Uodate fleet list
}
private void lstFleet_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstFleet.SelectedIndex > -1)
{
int index = lstFleet.SelectedIndex;
Car myCar = myFleet.fleet.ElementAt(index);
FrmCar carGui = new FrmCar();
carGui.car = myCar;
carGui.Show();
}
}
private void btnCustomer_Click(object sender, EventArgs e)
{
FrmCustomer customerGui = new FrmCustomer();
customerGui.ShowDialog();
Customer mycustomer = customerGui.customer;
mycustomer.addToClientList(mycustomer);
updateFleetList();
}
private void customers_SelectedIndexChanged(object sender, EventArgs e)
{
if (customers.SelectedIndex > -1)
{
int index = customers.SelectedIndex;
Customer myCustomer = mycustomer.clientlist.ElementAt(index);
FrmCustomer customerGui = new FrmCustomer();
customerGui.customer = myCustomer;
customerGui.Show();
}
}
}
为任何帮助干杯!
答案 0 :(得分:1)
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Vehicle c in myFleet.fleet)
{
string line = "Car: " + c.make+" " + c.colour;
lstFleet.Items.Add(line);
}
}
答案 1 :(得分:1)
您应该包括所有车辆。
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Vehicle v in myFleet.fleet)
{
lstFleet.Items.Add(v);
}
}
此外,只需覆盖所有Vehicle子类中的ToString
,ListBox
将固有地使用它;这样,并非每个Vehicle
都需要Make
或Color
属性。