簡體   English   中英

ListBox和對象屬性

[英]ListBox and object properties

一直在尋找一個明確的例子。 我創建了一個新對象,包括設置幾個屬性,將整個對象添加到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

只需將您的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...

更改選定索引后檢索雙精度值的示例:

窗體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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM