简体   繁体   English

如何在列表框选择上设置所选索引

[英]How to set selected index on listbox selection

I've done this before and got it fully working but i can't remember how 我之前已经做过,并且可以正常使用,但是我不记得如何

there's 3 properties behind my item class 我的物品类别后面有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;
       }
    }
}

now in my edit window 现在在我的编辑窗口中

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

i want the textboxes to reflect the Item Data behind the selected index. 我希望文本框反映所选索引后面的项目数据。 How is this possible. 这怎么可能。 I remember doing it before i just dont remember what method i used. 我记得这样做之前,我只是不记得我使用了什么方法。

Add selectedindexchanged event to your list box and then you can cast the selectedItem to a Item , now you can access the properties and set the text field of textboxes 将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;
}

if you need to update the items in the listbox you better implement INotifyPropertyChanged on ListBox Item 如果您需要更新列表框中的项目,则最好在ListBox Item上实现INotifyPropertyChanged

check this codeproject article 检查此代码项目文章

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

close to the last answer 接近最后一个答案

You can use SelectedItem 您可以使用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