简体   繁体   中英

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM