c# - 将项目从不同的类添加到列表框
问题描述
我想将项目添加到名为“mainFormRego”的列表框中。如果我在它所在的 MainForm 类中调用该方法,则该方法有效,但如果我尝试在不同的类中调用它,则它不起作用。我已经实例化了回调。请帮助我,我迷失了想法,并且一直在尝试寻找解决方案。我正在使用 C# 和 windows 窗体。
MainForm 类(列表框所在的位置)
namespace VehicleSystem
{
public partial class MainForm : Form
{
public void updateDisplay()
{
mainFormRego.Items.Clear();
foreach (Vehicle item in Business.VehicleList)
{
mainFormRego.Items.Add(item.Rego);
}
}
}
}
添加车辆类别
namespace VehicleSystem
{
public partial class AddVehicle : Form
{
public void addVehicle(string _rego, string _make, string _model, string _year, string _dailycharge)
{
MainForm fm = new MainForm();
fm.updateDisplay();
string[] inputs = { _rego, _make, _model, _year, _dailycharge };
bool status = true;
foreach (Vehicle item in Business.VehicleList)
{
if (item.Rego.ToString() == _rego)
{
MessageBox.Show("Error! Invalid input, please try agaian.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
status = false;
} else
{
status = true;
}
}
if (inputs.Any(x => string.IsNullOrWhiteSpace(x)))
{
MessageBox.Show("Error! Invalid input, please try agaain.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
} else if ( _year.Any(char.IsDigit) == false || _dailycharge.Any(char.IsDigit) == false)
{
MessageBox.Show("Error! Invalid input, please try agaain.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
} else if (status == true)
{
Business.VehicleList.Add(new Vehicle() { Rego = _rego, Make = _make, Model = _model, Year = _year, DailyCharge = _dailycharge });
this.Close();
}
}
}
}
车辆清单
namespace VehicleSystem
{
class Business
{
public const String fileName = "C:\\Users\\tbyrm\\Documents\\Workspace\\SDV601\\sdv601-s1-21-project-travisbyr\\save.dat";
private static List<Vehicle> vehicleList = new List<Vehicle>();
public static List<Vehicle> VehicleList { get => vehicleList; set => vehicleList = value; }
public static void Save()
{
using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fileStream, VehicleList);
}
}
public static void Retrieve()
{
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
VehicleList = (List<Vehicle>)formatter.Deserialize(fileStream);
}
}
public static void RemoveVehicle(string rego)
{
VehicleList.RemoveAll((x) => x.Rego == rego);
}
}
}
请帮忙!非常感谢任何帮助。
解决方案
问题是由于以下行引起的AddVehicle
:
MainForm fm = new MainForm();
您正在创建一个新实例,MainForm
而不是引用正在显示的当前活动实例。因此,您正确地更新了一个列表,但不是您期望的列表(在未显示 MainForm 的新实例上更新的列表)。
尝试mainFormRego
在另一个class
.
推荐阅读
- postgresql - PostgreSql 查询缓存逻辑
- kubernetes - Kubernetes 中的对象、资源和控制器
- python - “NoneType”对象没有“大小”属性 - 如何使用 mtcnn 进行人脸检测?
- r - R:如果值满足特定条件,如何将数据框转换为邻接矩阵?
- php - 如何使用多个获取请求 .htaccess
- javascript - 如何保持底部工具提示与其元素的右端对齐?
- c# - ListView 克隆移除了默认字体功能
- php - 如何从数组的特定对象中获取 id?
- javascript - 如何使用 Express res.send() 发送数组
- python - 在我的数据框上应用 PCA 后,它给了我一个奇怪的数字,它是什么意思或我该如何解释它?