【问题标题】:ListBox and object propertiesListBox 和对象属性
【发布时间】:2014-01-11 12:11:17
【问题描述】:

一直在寻找一个明确的例子。 我创建了一个新对象,包括设置几个属性,将整个对象添加到 listBox,然后写了一个字符串来描述它们。现在,我想要选定索引处的 lsitBox 对象中的一项。有许多语法似乎具有相似但不同的用法,这使搜索变得复杂......

Pseudocode:
SpecialClass object = new SpecialClass;
object.propertyA;
Object.PropertyB;

listBox.Items.Add(object);

//listBox.SelectedItem[get propertyA]? What would retrieve propertyA or propertyB from the //list after putting the object in the list?

....我尝试使用这个变量设置,类似这样...

 MRecipeForm parent = new MRecipeForm();
            ListViewItem item = new ListViewItem();
            item.Tag = parent.recipeListB.Items;

            var myObject = (double)parent.recipeListB.SelectedItems[0].Tag;
            // here you can access your properties myObject.propertA etc...

....

这是我当前抛出异常的代码:

  MRecipeForm parent = new MRecipeForm();
            ListViewItem item = new ListViewItem();
            item.Tag = parent.recipeListB.Items;

            Substrate o = ((ListBox)sender).SelectedItem as Substrate;
            double dryWtLbs = o.BatchDryWtLbs; //BatchDryWtLbs is type double

【问题讨论】:

标签: c# listbox


【解决方案1】:

只需将您的object 存储到您项目的Tag 属性中。添加项目时:

ListViewItem item = new ListViewItem();
item.Tag = myObject;
...

然后:

var myObject = (SpecialClass)listBox.SelectedItems[0].Tag;
// here you can access your properties myObject.propertA etc...

【讨论】:

  • 我需要从列表中访问一个 double,如何转换它?
  • @CodeMatrix:你不需要强制转换它。当您将项目投射到 SpecialClass 时,您可以在不投射的情况下访问其属性。
  • 我已经为此工作了几天,并且接近答案!谢谢!
  • 得到这个异常:'System.InvalidCastException'
【解决方案2】:

更改选定索引后检索双精度的示例:

Forms 1 有一个标签:label1 和一个列表框:listBox1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var object1 = new SpecialClass { Text = "First line", Number = 1d };
        var object2 = new SpecialClass { Text = "Second line", Number = 2d };
        listBox1.Items.Add(object1);
        listBox1.Items.Add(object2);
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        SpecialClass o = ((ListBox)sender).SelectedItem as SpecialClass;
        label1.Text = o.Number.ToString();
    }
}

public class SpecialClass
{
    public string Text { get; set; }
    public double Number { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多