This problem should be simple.
I am using Visual Studio 2003, Version 1.1
I am writing a desktop application in which I am binding a DataTable
to the DataSource of a ComboBox.
// I have 50 rows (concerning states) in dataTable.Rows;
ComboBox myComboBox = new ComboBox();
myComboBox.DataSource = dataTable;
myComboBox.DisplayMember = "state_name";
myComboBox.ValueMember = "state_id";
myComboBox.SelectedIndex = 3;
I get an exception stating that '3' is out of range, because
myComboBox.Items.Count = 0, not 50.
How can I set SelectedIndex when using a DataSource?
A very messy workaround is to add the items in a loop, but I would
like to use the power of DataSource.
P.S. In ASP.NET they have a DataBind() method which is absent for a
desktop application.
Thanks for your help.
Mufaka - 29 Feb 2008 21:14 GMT
Try adding a dummy binding context to it before setting the DataSource.
I think that will trick the ListControl into populating items when the
DataSource is set.
ComboBox myComboBox = new ComboBox();
myComboBox.BindingContext = new BindingContext();
...
> This problem should be simple.
>
[quoted text clipped - 23 lines]
>
> Thanks for your help.
samueltilden@gmail.com - 29 Feb 2008 22:01 GMT
Mufaka:
Thanks so very much!
That works!
--Sam