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

本文关键字:设置 索引 选择 列表 | 更新日期: 2023-09-27 18:31:48

我以前做过这个并让它完全工作,但我不记得如何

我的项目类后面有 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;
}