On Tue, 17 Jul 2007 14:48:03 +0200, Stephen Ritchie <St************@discussions.microsoft.comwrote:
Hi
NET1.1 / Winforms
I have a listbox that I am binding to a table via the DataSource property.
However I want to be able to programmatically select values in this listbox
so I am using the code below...
With lstJobTypes
.DataSource = BusinessRules.Common.JobTypes.All(True)
.DisplayMember = "Description"
.ValueMember = "JobTypeID"
End With
If Not _DefaultJobTypes Is Nothing Then
For Each j As PlasmaCommon.JobType In m_DefaultJobTypes
lstJobTypes.SelectedValue = CInt(j)
Next
End If
If I step through using the debugger, I can see the
lstJobTypes.SelectedItems.Count property increasing everytime I set the
SelectedValue and all seems good.
However when the form is then displayed the Count property becomes 1 and
only the first item in the listbox (standard functionality) is selected??!?!?!
The listbox selection mode is set to MultiExtended.
This also happens if I use the SetSelected method rather than the
SelectedValue method.
Any help is greatly appreciated as I am pulling my hair out here :(
Hi Stephen,
I did a test and could not immediatly reproduce your problem (C# code added below), but then I noticed "... when the form is displayed". Are you by chance running this code in the constructor? DataBindings can be tricky and some do not perform well at all if you manipulate them before the controls have been created.
If you are running the code in the constructor, try moving it to the load event instead. (I did get the same problem if I ran the code from the constructor, but it worked fine from the load event or using a button totrigger it).
protected override void OnLoad(EventArgs e)
{
base.OnLoad (e);
button1_Click(this, null);
}
int[] def = new int[]{1, 3, 5};
private void button1_Click(object sender, System.EventArgs e)
{
ArrayList list =new ArrayList();
list.Add(new MyObj("Zero", 0));
list.Add(new MyObj("One", 1));
list.Add(new MyObj("Two", 2));
list.Add(new MyObj("Three", 3));
list.Add(new MyObj("Four", 4));
list.Add(new MyObj("Five", 5));
list.Add(new MyObj("Six", 6));
listBox1.DataSource = list;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "ID";
listBox1.SetSelected(0, false); // to prevent the default item selected
foreach(int i in def)
{
listBox1.SelectedValue = i;
}
}
class MyObj
{
private string _Name;
private int _ID;
public string Name
{
get{return _Name;}
set{_Name = value;}
}
public int ID
{
get{return _ID;}
set{_ID = value;}
}
public MyObj(string name, int id)
{
this.Name = name;
this.ID = id;
}
}
--
Happy coding!
Morten Wennevik [C# MVP]