簡體   English   中英

如何在列表框選擇上設置所選索引

[英]How to set selected index on listbox selection

我之前已經做過,並且可以正常使用,但是我不記得如何

我的物品類別后面有3個屬性

namespace Budgeting_Program
{    
    [Serializable]
    public class Item
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public string @URL { get; set; }

        public Item(string Name, string Price, string @URL)
        {
            this.Name = Name;
            this.Price = Convert.ToDouble(Price);
            this.@URL = @URL;
        }

        public override string ToString()
        {
            return this.Name;
       }
    }
}

現在在我的編輯窗口中

public Edit(List<Item> i, int index)
{
    InitializeComponent();
    itemList = i;
    updateItemList();    
    itemListBox.SetSelected(index, true);                               
}

我希望文本框反映所選索引后面的項目數據。 這怎么可能。 我記得這樣做之前,我只是不記得我使用了什么方法。

將selectedindexchanged事件添加到列表框中,然后可以將selectedItem強制轉換為Item ,現在您可以訪問屬性並設置文本框的文本字段

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
   Item item = (Item)listBox1.SelectedItem;
   txtName.Text = item.Name;
   txtPrice.Text = item.Price;
   txtUrl.Text = item.Url;
}

如果您需要更新列表框中的項目,則最好在ListBox Item上實現INotifyPropertyChanged

檢查此代碼項目文章

 Item found = itemList.Find(x => x.Name == (string)itemListBox.SelectedItem);
        if (found != null)
        {
            nameText.Text = found.Name;
            priceText.Text = Convert.ToString(found.Price);
            urlText.Text = found.URL;
        }

接近最后一個答案

您可以使用SelectedItem

var selection = itemListBox.SelectedItem as Item;
if (selection != null)
{
   textboxName.Text = selection.Name;
   textboxPrice.Text = selection.Price;
   textboxUrl.Text = selection.Url;
}

暫無
暫無

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

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