C#如何按日期对组合框项目进行排序

时间:2017-09-28 07:33:12

标签: c# sql database combobox

    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);
        }
    }

What the database looks like

我无法弄清楚如何按照日期对组合框中列出的项目进行排序,只显示其名称

3 个答案:

答案 0 :(得分:2)

    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);
        }
    }

这为我修好了

答案 1 :(得分:0)

在将日期添加到组合框之前对日期进行排序。使用“ORDER BY”,内容按字符串表示排序。

确保自动排序。

Source

答案 2 :(得分:0)

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

}