【问题标题】:Getting an object from a ComboBox BindingSource从 ComboBox BindingSource 获取对象
【发布时间】:2019-08-18 11:30:47
【问题描述】:

我正在使用 C# Winforms 开展一个学校项目,我必须创建一个车辆销售发票并打开一个新表单,其中包含从组合框中选择的车辆信息。如何根据组合框中的 SelectedItem 获取 Vehicle 对象或其属性?

Vehicle 对象位于一个列表中,该列表绑定到绑定到组合框的 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();
        }

【问题讨论】:

  • 然后将您想要的对象传递给该表单。最好使用自定义构造函数:public VehicalInformation(Vehicle vehicle) {...}
  • 或添加(到VehicleInformation 表单)接受Vehicle 类型参数的公共属性或方法。您可以在显示之前设置它。或者之后,如你所愿。

标签: c# winforms data-binding combobox


【解决方案1】:
  1. 开启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";
    }
    
  2. 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);
        }
    }
    
  3. 现在在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());
       }
    }
    

【讨论】:

  • 由于您使用的是 BindingSource,您可以将 Binding 添加到 Label,设置为 Text 属性、BindingSource、绑定的类属性并指定 DataSourceUpdateMode.OnPropertyChangedSelectedIndexChanged 处理程序可以删除,因为数据更改通知由 BindingSource 处理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多