ComboBox Setting both DataSource and SelectedIndex

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • samueltilden@gmail.com

    ComboBox Setting both DataSource and SelectedIndex

    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.Data Source = dataTable;
    myComboBox.Disp layMember = "state_name ";
    myComboBox.Valu eMember = "state_id";
    myComboBox.Sele ctedIndex = 3;

    I get an exception stating that '3' is out of range, because
    myComboBox.Item s.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

    #2
    Re: ComboBox Setting both DataSource and SelectedIndex

    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.Bind ingContext = new BindingContext( );
    ....


    samueltilden@gm ail.com wrote:
    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.Data Source = dataTable;
    myComboBox.Disp layMember = "state_name ";
    myComboBox.Valu eMember = "state_id";
    myComboBox.Sele ctedIndex = 3;
    >
    I get an exception stating that '3' is out of range, because
    myComboBox.Item s.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.

    Comment

    • samueltilden@gmail.com

      #3
      Re: ComboBox Setting both DataSource and SelectedIndex

      Mufaka:

      Thanks so very much!

      That works!

      --Sam

      Comment

      Working...