在txt文件里进行查询(winform案例简单)

在txt文件里进行查询(winform案例简单)_第1张图片

如上图所示布局,打开成绩单按钮必须先点击一下才能查询某个人的成绩,其功能主要是为了获取openfiledialog的filename即打开文件的地址。

打开成绩单按钮代码:

<textarea cols="50" rows="15" name="code" class="c-sharp"> if (openFileDialog1.ShowDialog() == DialogResult.OK) { string filename = openFileDialog1.FileName; } </textarea> 

查询按钮代码:

<textarea cols="50" rows="15" name="code" class="c-sharp"> //用户在点击成绩单ok的情况下 string filename = openFileDialog1.FileName; //判断用户有没有打开查询文件 if (string.IsNullOrEmpty(filename)) { MessageBox.Show("没有打开查询文件"); } else { //判断用户是否输入空字段 if (string.IsNullOrEmpty(txtName.Text.Trim())) { MessageBox.Show("请输入姓名"); } else { string[] lines = File.ReadAllLines(filename); //判断是否查到结果 bool find = false; foreach (var line in lines) { string[] strs = line.Split('|'); string name = strs[0]; string scores = strs[1]; if (name == txtName.Text.Trim()) { MessageBox.Show(name + "的成绩为:" + scores); find = true; //之后还有代码要执行,所以不能return break; } } if (find == false) { MessageBox.Show("没有查到此人分数"); } } } </textarea> 

你可能感兴趣的:(String,WinForm)