【问题标题】:Access parameters from an object listed in a listbox c#从列表框 c# 中列出的对象访问参数
【发布时间】:2017-12-05 15:15:04
【问题描述】:

我的程序中有几个类,我正在使用 Windows 窗体从不同的类创建对象并将它们列在不同的列表框中。

现在我有一个包含所有列表框的表单(表单 1)和另一个表单(CreerVoiture),我将所有信息放入其中以创建我选择的对象。

一个例子是当我点击按钮“Voiture!”我的第二个表单打开,当我添加所有信息并按下“Ajouter”时,它会将对象添加到选定的列表框中。

Form1 中的代码:

private void button1_Click(object sender, EventArgs e)
    {
        CreerVoiture creervoiture = new CreerVoiture();
        if (creervoiture.ShowDialog(this) == DialogResult.OK)
        {
            // Read the contents of form2's TextBox.
            Voiture voiture = new Voiture(creervoiture.GetMarque(), creervoiture.GetPrix(), creervoiture.GetConsommation(), creervoiture.GetReservoir());
            this.list_voiture.Items.Add(voiture);

            this.list_voiture.DataSource = null;
        }
        creervoiture.Dispose();
    }

我想知道的是,在将第二个表单中添加的参数添加到列表框后,如何访问它。

我正在考虑使用类似的东西:

list_voiture.SelectedItem.Prix

Prix 是我班 Voiture 的吸气剂

public double Prix
    {
        get { return this.prix; }
        set { this.prix = value; }
    }

但这似乎是不可能的。这可能吗?如果可以,怎么做?

提前致谢,

杰里米

【问题讨论】:

  • 使用ListBox.Items 遍历ListBox 中的所有项目。如果您只需要 SelectedItem,则使用 ListBox.SelectedItem 属性。此外,您需要将属性转换为Voiture,然后访问属性。
  • 您好,谢谢您的回答。您能否详细说明您的答案,我不知道您将属性转换为 Voiture 是什么意思。谢谢
  • var selectedItem = list_voiture.SelectedItem as Voiture

标签: c# winforms class listbox listboxitem


【解决方案1】:

如果对象的类型是Voiture,那么您可以将对象强制转换为该类型:

Voiture voiture = (Voiture)list_voiture.SelectedItem;
double prix = voiture.Prix;

或者在一行中:

double prix = ((Voiture)list_voiture.SelectedItem).Prix;

【讨论】:

  • 感谢您的回答。我对表格很陌生,所以还是有点困惑。我在我的表单上添加了一个按钮,如果我点击它,它应该在 Label1 中写下汽车的价格(Prix)。 private void button1_Click_1(object sender, EventArgs e) { double prix = ((Voiture)list_voiture.SelectedItem).Prix; label1.Text = prix.ToString(); } 但它不起作用。当我点击按钮时什么都没有发生。我做错了什么?
  • 没关系 :) 我忘了把方法链接到我的按钮...谢谢你的信息!
猜你喜欢
  • 1970-01-01
  • 2020-03-31
  • 2011-09-12
  • 2017-02-02
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
相关资源
最近更新 更多