我正在使用C#Winforms在一个学校项目中工作,在该项目中,我必须创建车辆销售发票并使用包含从组合框中选择的车辆信息的新表格来进行操作。如何根据组合框中的SelectedItem获取Vehicle对象或其属性?
Vehicle对象位于绑定到BindingSource的列表中,该BindingSource绑定到组合框。 我能够将静态字符串传递到此分配的另一个组件中的新表单中,但是我不知道如何检索对象信息。
我绑定到组合框的车辆列表。 DataRetriever是我们为我们提供Vehicle对象的类。它们具有自动实现的属性(品牌,型号,id,颜色等)
List<Vehicle> vehicles = DataRetriever.GetVehicles();
BindingSource vehiclesBindingSource = new BindingSource();
vehiclesBindingSource.DataSource = vehicles;
this.cboVehicle.DataSource = vehiclesBindingSource;
this.cboVehicle.DisplayMember = "stockID";
this.cboVehicle.ValueMember = "basePrice";
我希望能够将信息传递到此表单并使用标签显示有关所选车辆的信息。
private void vehicleInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
VehicleInformation vehicleInformation = new VehicleInformation();
vehicleInformation.Show();
}
答案 0 :(得分:0)
在Form_Load
List<VecDetails> lstMasterDetails = new List<VecDetails>();
private void frmBarcode_Load(object sender, EventArgs e)
{
VechicleDetails();
BindingSource vehiclesBindingSource = new BindingSource();
vehiclesBindingSource.DataSource = lstMasterDetails;
this.comboBox1.DataSource = vehiclesBindingSource;
this.comboBox1.DisplayMember = "stockID";
this.comboBox1.ValueMember = "basePrice";
}
在VechicleDetails()
方法中,我只是生成样本值,因此我可以将它们转换为ComboBox
private void VechicleDetails()
{
//Sample Method to Generate Some value and
//load it to List<VecDetails> and then to ComboBox
for (int n = 0; n < 10; n++)
{
VecDetails ve = new VecDetails();
ve.stockID = "Stock ID " + (n + 1).ToString();
ve.basePrice = "Base Price " + (n + 1).ToString();
lstMasterDetails.Add(ve);
}
}
现在comboBox1_SelectedIndexChanged
事件中,我正在获取所选项目的值
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string strStockId = comboBox1.Text.ToString();
string strBasePrice = (comboBox1.SelectedItem as dynamic).basePrice;
label1.Text = strStockId + " - " + strBasePrice;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}