Domanda

In my database the primary keys are in order from least to greatest (1,2,3, etc.) but when I load them into my combobox they are displayed out of order. I'm sure there is an easy fix to this, but I'm stuck.

    public void fillComboBox()
    {
        try
        {
            // query to pull invoice ids
            string sql = "SELECT PersonalInfo.[ID] FROM PersonalInfo order by ID"; 

            // adapter to send query to database
            OleDbDataAdapter daInvoices = new OleDbDataAdapter(sql, Conn);
            // fill dataset
            daInvoices.Fill(cusNumDS, "PersonalInfo");

            // declare data source for invoice id combo box
            custCB.DataSource = cusNumDS.Tables[0];
            custCB.DisplayMember = "PersonalInfo";
            custCB.ValueMember = "ID";
            // bind data source to combo box
            custCB.DataBindings.Add("SelectedValue", cusNumDS.Tables[0], "ID");
        }
        catch (Exception ex)
        {
            // error message if trouble pulling invoice ids from database
            MessageBox.Show("Trouble pulling invoices from database because: " + ex,
                "Database Error",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }
È stato utile?

Soluzione 2

From a comment, you say..

No the combobox displays everything that begins with 1, such as 1, 10, 11, 12...2, 20, 21, 22 etc. I want it to be in order from lowest to highest.

This means a Lexicographical Ordering for text is being used during the sorting. Now, there are two reasons (I can think of) that would cause this.

  1. The KEY might be a char/varchar column and the ordering is applied by the database. If this is the case, then the following query should work:

    SELECT PersonalInfo.[ID] FROM PersonalInfo
    ORDER BY CAST(id AS INT)
    -- for MS Access maybe: ORDER BY CInt(id)
    

    And if it does fix the problem then the scheme should probably be fixed!

  2. A sort might be applied after the query, such as within the ComboBox itself! Make sure that Sorted is false.

    [The Sorted] property specifies whether the ComboBox sorts existing entries and add new entries to the appropriate sorted position in the list. You can use this property to automatically sort items in a ComboBox .. The sort is case-insensitive and in alphabetically ascending order.

.. or it could be a combination of both! Also, make sure that the code being run/tested is the latest version and is really being used.

Altri suggerimenti

SELECT PersonalInfo.[ID] FROM PersonalInfo order by 1 ASC

try this....

SELECT PersonalInfo.[ID] FROM PersonalInfo order by ID ASC

put ASC at the end of your select statement

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top