Windows Develop Bookmark and Share   
 index > Windows Forms Designer > ListBox - SelectedItem
 

ListBox - SelectedItem

Hi

I don't know why but suddenly when I set lst.SelecteItem = obj it doesn’t work (It doesn’t find my object in the collection) and I know that it exist in the list.

Any ideas?

Thanks

Itzik Kramer  Sunday, March 02, 2008 1:13 PM

Hi,

Please make sure the obj is in the Collection, it should be the exact object that exists in the collection that is not a copy. Something like this works well.

Code Snippet

partial class Form21 : Form

public Form21()

private void Form21_Load(object sender, EventArgs e)

new OBJ(1));

new OBJ(2));

new OBJ(3));

new OBJ(4));

//bothwaysto populate the ListBox will workwell
//1. Data binding

//this.listBox1.DataSource = objs;
//2.Add items manually

foreach (OBJ o in objs)

this.listBox1.Items.Add(o);

List<OBJ> objs= new List<OBJ>();

private void button1_Click(object sender, EventArgs e)

this.listBox1.SelectedItem = objs[2];

class OBJ

private int id;

public OBJ(int id)

this.id = id;

public int Id

get { return id; }

set { id = value; }

public override string ToString()

return id.ToString();

Could you paste your code here and tell me your reqirement .

jsj_Samson  Tuesday, March 04, 2008 8:07 AM

Hi

My datasource is collection thatI created

and I am setteing it by "lst.SelectedItem = MyObject"

Itzik Kramer  Thursday, March 06, 2008 6:32 AM

Hi,

Please make sure the obj is in the Collection, it should be the exact object that exists in the collection that is not a copy. Something like this works well.

Code Snippet

partial class Form21 : Form

public Form21()

private void Form21_Load(object sender, EventArgs e)

new OBJ(1));

new OBJ(2));

new OBJ(3));

new OBJ(4));

//bothwaysto populate the ListBox will workwell
//1. Data binding

//this.listBox1.DataSource = objs;
//2.Add items manually

foreach (OBJ o in objs)

this.listBox1.Items.Add(o);

List<OBJ> objs= new List<OBJ>();

private void button1_Click(object sender, EventArgs e)

this.listBox1.SelectedItem = objs[2];

class OBJ

private int id;

public OBJ(int id)

this.id = id;

public int Id

get { return id; }

set { id = value; }

public override string ToString()

return id.ToString();

Thanks

Itzik Kramer  Thursday, March 06, 2008 10:05 AM

You can use google to search for other answers

Custom Search

More Threads

• Listbox Ownerdraw-Problem
• Web Forms Editor
• DatetimePicker in datagridview
• HELP ME!!!!!!
• Windows Impersonation Context and Web Browser Control.
• Strange behavior of CollectionEditor with my collection
• Change MenuStrip Color
• Create custom Controls for Win Forms book, sample, etc
• Transparent User Control in VB.NET
• back color problem