ComboBox Setting both DataSource and SelectedIndex

S

samueltilden

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.
 
M

Mufaka

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();
....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top