gpt4 book ai didi

c# - 排序组合框时出现问题

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:00 25 4
gpt4 key购买 nike

我正在执行一项任务,我需要通过列表填充组合框,而列表是从 employee.dat 文件填充的。我已成功填充组合,但在对其进行排序时遇到问题。我要排序的值是字符串数字。它显示 0-9 的值,但当它超出 9 时,组合看起来很傻。

这是截图

enter image description here

我需要做的是对这些值进行排序,意味着 10 应该领先 9。

这是我已经尝试过的代码片段。

         private void FormDelete_Load(object sender, EventArgs e)
{
//LOAD EVENT for FORM

//Clear all form controls
Reset();

//Fill the ID Combo box using data in List<T>
comboBoxID.Items.Clear();
foreach (MyClass.Employee obj in MyClass.listEmployees)
{
comboBoxID.Items.Add(obj.ID);
}

//Sort the combo box ibn ascending order
comboBoxID.Sorted = true;

}

Employee.cs

    public class Employee
{
public int ID;
public string fName;
public string lName;
public string gender;
public int age;
public double hourWage;

}
public static List<Employee> listEmployees = new List<Employee>();

员工.dat

1, Ann, Crowe, F, 34, 12.95
2, Bob, Costas Jr., M, 27, 8.75
3, Sue, Soppala, F, 22, 7.95
4, Bill, Barton, M, 45, 15.25
5, Jill, Jordan, F, 33, 14.75
6, Art, Ayers, M, 33, 14.75
7, Larry, Stooge, M, 55, 21.05
8, Art, Ayers, M, 33, 14.75
9, Larry, Stooge, M, 55, 21.05
10, Art, Ayers, M, 33, 14.75
11, Larry, Stooge, M, 55, 21.05

列表填充代码

 if (File.Exists("employee.data"))
{
try
{
streamEmployee = new StreamReader("employee.data");
string line; //to read a line from the text file
string[] arrFields = new string[5];
while (streamEmployee.Peek() > -1)
{
line = streamEmployee.ReadLine(); //read a line of records from file
arrFields = line.Split(','); //split the line at comma junction, and save split //fields in array

MyClass.Employee objEmp = new MyClass.Employee(); //create a "specific" employee //object instance

//Assign each field from line as generic object's properties to make it "specific
objEmp.ID = Convert.ToInt32(arrFields[0].Trim()); //ID is integer
objEmp.fName = arrFields[1].Trim();
objEmp.lName = arrFields[2].Trim();
objEmp.gender = arrFields[3].Trim();
objEmp.age = Convert.ToInt32(arrFields[4].Trim()); //age is integer
objEmp.hourWage = Convert.ToDouble(arrFields[5].Trim()); //hourly wage is double

//Add this specific employee object to the List
MyClass.listEmployees.Add(objEmp);

} //while


} //try

catch (IOException err)
{
MessageBox.Show(err.Message);
error = true;

} //catch

finally
{
if (streamEmployee != null) //it is indeed representing a file and may not be closed
streamEmployee.Close();


} //finally

} //if

最佳答案

您的文件已经排序,因此无需调用 Sorted=true。
无论如何,如果您想确保无论输入文件中存在什么顺序,您的代码都会按照 ID 顺序添加员工,那么您可以将循环更改为

foreach (MyClass.Employee obj in MyClass.listEmployees.OrderBy(x => x.ID))
{
comboBoxID.Items.Add(obj.ID);
}

同样不需要将 Sorted 属性设置为 true....

关于c# - 排序组合框时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36602914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com