簡體   English   中英

C#如何按日期對組合框項目進行排序

[英]C# How to sort combobox items by date

    void Fillcombo()
    {
        cbxProducts.Text = "";
        cbxProducts.Items.Clear();
        string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
        string Query = "SELECT Name FROM Products;";
        SqlConnection conDataBase = new SqlConnection(constring);
        SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
        SqlDataReader myReader;
        try
        {
            conDataBase.Open();
            myReader = cmdDataBase.ExecuteReader();
            while (myReader.Read())
            {

                string sName = myReader.GetString(myReader.GetOrdinal("Name"));
                cbxProducts.Items.Add(sName);
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

數據庫的外觀

我不知道如何在組合框中列出的項目按日期排序,而只顯示其名稱

    void Fillcombo()
    {
        cbxProducts.Text = "";
        cbxProducts.Items.Clear();
        string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
        string Query = "SELECT Name FROM Products ORDER BY EDate;";
        SqlConnection conDataBase = new SqlConnection(constring);
        SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
        SqlDataReader myReader;
        try
        {
            conDataBase.Open();
            myReader = cmdDataBase.ExecuteReader();
            while (myReader.Read())
            {

                string sName = myReader.GetString(myReader.GetOrdinal("Name"));
                cbxProducts.Items.Add(sName);
                cbxProducts.Sorted = false;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

這為我解決了

對日期進行排序,然后將其添加到組合框。 使用“ ORDER BY”,內容以字符串表示形式排序。

確保打開自動分類功能。

資源

public class YourObject : IComparable{
public YourObject(string name) {
    Name = name;
}
public string Name { get; set; }
public override string ToString()
{
    return GetHashCode().ToString() + "_" + Name;
}

#region IComparable Members

public int CompareTo(Object other)
{
    return Comparer.Default.Compare(this.ToString(), other.ToString());
}

#endregion

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM