[英]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);
}
}
這為我解決了
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.