因此,我一直在撞墙,试图用保存在文本文件中的ID号填充此列表框。将行从文件中取出并放入这样的列表框中非常简单,但是该ID号也与我想在其他文本框中显示的更多信息共享。
简而言之,我有一个文本文件,其中包含多个ID号,名称和地址,但是我只想显示ID号,以便可以从列表框中单击它们,其余的该信息可以显示在屏幕上。
我已经接受了很多建议,但是我的头脑很笨拙,无法找出几个关键点。让我从共享到目前为止的代码开始:
List<String> colStudents = new List<String>();
public MainWindow()
{
InitializeComponent();
}
private void btnGetStudents_Click(object sender, RoutedEventArgs e)
{
try
{
int intIndex;
string strStudentInfo;
string strStudentID;
//Define a Student object variable with the name StudentInfo
string StudentInfo;
// Declare a StreamReader variable for Student Object
StreamReader Student = new StreamReader("StudentData.txt");
// intIndex is the index of the contact chosen
intIndex = lstStudentsID.SelectedIndex;
// Add student to colStudents list
colStudents.Add(Student.ToString());
// Read the disk file structure
while (Student.EndOfStream == false)
{
// Read disk file into a string variable using the ReadLine method.
strStudentInfo = Student.ReadLine();
// Tokenize the string read from Student object
string[] tokenize = strStudentInfo.Split(',');
// Create a student object instance from the Student class.
string temp = tokenize[0];
// Set properties of Student object to array element containing the student data
// Add student object to collection
}
//Close disk file after all records have been read in
Student.Close();
}
catch(Exception ex)
{
MessageBox.Show("Experiencing the following disk problems: " + Environment.NewLine + ex.Message, "Disk File", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
[我的头无法绕开如何从数组中获取元素的方法,就像我的string []标记化行一样。另外,学生对象或学生班级可能意味着什么?我也得到了这个神秘的建议:
如何获取学生信息?
定义整数变量intIndex
用名称StudentInfo定义Student对象变量
将intIndex设置为ListBox的SelectedIndex。
将StudentInfo设置为colStudents [?]
我的strStudentInfo变量不应该是建议中的学生信息。
您以Key为学生ID和值作为文件行创建字典然后使用字典,您可以填充列表框当用户选择特定列表项从字典中检索数据时,请勿执行IO操作。
Dictionary studentInfo = new Dictionary();
static void Main(string[] args)
{
StreamReader Student = new StreamReader("StudentData.txt");
// intIndex is the index of the contact chosen
intIndex = lstStudentsID.SelectedIndex;
// Add student to colStudents list
colStudents.Add(Student.ToString());
// Read the disk file structure
while (Student.EndOfStream == false)
{
// Read disk file into a string variable using the ReadLine method.
strStudentInfo = Student.ReadLine();
// Tokenize the string read from Student object
string[] tokenize = strStudentInfo.Split(',');
// Create a student object instance from the Student class.
string temp = tokenize[0];
studentInfo.Add("Key", strStudentInfo);
}
}