MikaAK
MikaAK

Reputation: 2364

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.

Upvotes: 0

Views: 1037

Answers (3)

MikaAK
MikaAK

Reputation: 2364

 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

Upvotes: 1

Damith
Damith

Reputation: 63105

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

Upvotes: 2

sa_ddam213
sa_ddam213

Reputation: 43636

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

Upvotes: 0

Related Questions