【发布时间】:2016-04-13 15:21:14
【问题描述】:
我正在处理一项任务,我需要通过 List 填充组合框,并且 List 是从 employee.dat 文件填充的。我成功地填充了组合,但是在对其进行排序时遇到了一个问题。我要排序的值是字符串数字。它显示了 0-9 的值,但当它超过 9 时,组合看起来很傻。
这是截图
我需要做的是对这些值进行排序,意味着 10 应该领先 9。
这是我尝试过的代码sn-p。
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>();
Empolyee.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 行,您的项目已经按正确的顺序排列
-
@Steve 感谢您的回复,我已经尝试过了,它可以工作。但是,如果我从输入源文件更改顺序怎么办?注释掉已排序的行不是解决方案。
-
刚刚为这个案例添加了一个答案