按int值排序一个组合框

本文关键字:一个 组合 int 排序 | 更新日期: 2023-09-27 17:49:48

按值排序我的组合框有很多问题,非常感谢任何帮助

   private void Form1_Load(object sender, EventArgs e)
    {
        //text to hold the conbo box, text is grabed from the AS2W14data.csv file from c:'temp'...
        String variable;
        variable = "";
        //filll in the combo box , create a reader
        System.IO.StreamReader sr = System.IO.File.OpenText(@"c:'temp'AS2W14data.csv");
        //use a while loop to read the entire file line by line, using the current line to populate the comboBox
        while (!sr.EndOfStream)
        {
            variable = sr.ReadLine();
            string[] currentLineIndex = variable.Split(',');
            //customer ID is indexed at the string array postion 1
            //Customer name is indexed at the string array position 0
            cboCustomer.Items.Add(currentLineIndex[1].Trim() + " " + currentLineIndex[0].Trim());
        }
        //close the file to prevent errors...
        sr.Close();
    }

这是我的代码到目前为止,我似乎找不到一种方法来订购它…帮助

按int值排序一个组合框

我建议在将它们添加到组合之前先订购它们。这里还有一个阅读文本文件的快捷方式。首先,您想通过流式传输它们(ReadLines()返回IEnumerable<string>)来读取行(Select()),在其中创建一个具有两个属性的匿名对象- IdName。最后,您通过Id订购这些匿名对象的集合。

var lines = File.ReadLines(@"c:'temp'AS2W14data.csv")
                .Select(l => new 
                { 
                    Id = int.Parse(l.Split(',')[1].Trim()), 
                    Name = l.Split(',')[0].Trim() 
                }).OrderBy(i => i.Id);
foreach (var l in lines)
    cboCustomer.Items.Add(l.Id + " " + l.Name);

试试这个代码,希望它能工作,或者你可以使用ComboBoxSorted属性

private void Form1_Load(object sender, EventArgs e)
{
    //text to hold the conbo box, text is grabed from the AS2W14data.csv file from c:'temp'...
    String variable;
    variable = "";
    ArrayList Indexs = new ArrayList();
    //filll in the combo box , create a reader
    System.IO.StreamReader sr = System.IO.File.OpenText(@"c:'temp'AS2W14data.csv");
    //use a while loop to read the entire file line by line, using the current line to populate the comboBox
    while (!sr.EndOfStream)
    {
        variable = sr.ReadLine();
        string[] currentLineIndex = variable.Split(',');
        //customer ID is indexed at the string array postion 1
        //Customer name is indexed at the string array position 0
        Indexs.Add(new AddIndexValues(currentLineIndex[1].Trim() + " " + currentLineIndex[0].Trim());
    }
    //close the file to prevent errors...
    cboCustomer.DataSource = DataBaseBuilds.Indexs;
    sr.Close();
}
public class AddIndexValues
{
   private int i_index;
   public AddIndexValues(int Index)
   {
      i_index = Index;
   }
   public int Index
   {
      get { return i_index; }
   }
}