C# WinForms中如何避免向ListBox添加重复Student条目
问题描述
我正在开发基于.NET Framework的C# Windows Forms应用,定义了包含Name、LastName、Classroom、DateDay属性的Student类。通过三个TextBox和一个DateTimePicker收集数据,将条目保存至List<Student>和ListBox中。需要在添加条目前检查是否已存在重复项:若重复则弹出错误提示框,否则执行添加操作。但尝试的重复检查逻辑存在问题,不知道如何正确使用foreach循环检查List或ListBox中的条目。
我的重复检查尝试代码
private void btnAdding_Click(object sender, EventArgs e) { if (txtName.Text != "" && txtLastName.Text != "" && txtClassroom.Text != "" ) { if (ListBox.Items.Cast<string>().Contains(ListBox.Items.ToString())) { MessageBox.Show("This entry already exists.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { List.Add(new Student(txtName.Text, txtLastName.Text, txtClassroom.Text, dateDay.Value.ToString("dd.MM.yyyy"))); RefreshCheck(); } } else { MessageBox.Show("You didnt fill out all the text boxes.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void RefreshCheck() { ListBox.Items.Clear(); for (int i = 0; i < seznam.Count(); i++) { ListBox.Items.Add(List[i].StudentAdd()); this.txtName.Clear(); this.txtLastName.Clear(); this.txtClassroom.Clear(); this.dateDay.Value = DateTime.Today; this.tabStudent.SelectedTab = this.tabCheck; } }
无重复检查的原始代码
private void btnAdding_Click(object sender, EventArgs e) { if (txtName.Text != "" && txtLastName.Text != "" && txtClassroom.Text != "" ) { List.Add(new Student(txtName.Text, txtLastName.Text, txtClassroom.Text, dateDay.Value.ToString("dd.MM.yyyy"))); RefreshCheck(); } else { MessageBox.Show("You didnt fill out all the text boxes.", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void RefreshCheck() { ListBox.Items.Clear(); for (int i = 0; i < List.Count(); i++) { ListBox.Items.Add(List[i].StudentAdd()); this.txtName.Clear(); this.txtLastName.Clear(); this.txtClassroom.Clear(); this.dateDay.Value = DateTime.Today; this.tabStudent.SelectedTab = this.tabCheck; } }
其他相关代码
添加至List的代码
List.Add(new Student(txtName.Text, txtLastName.Text, txtClassroom.Text, dateDay.Value.ToString("dd.MM.yyyy")));
Student类的StudentAdd方法
public string StudentAdd() { return $"{this.Name} {this.LastName} | {this.Clasroom} | {this.DateOfLeave}"; }
注:已将OsveziPregledDijaka()更改为RefreshCheck,并补充了该函数代码。
错误分析
你当前的重复检查逻辑ListBox.Items.Cast<string>().Contains(ListBox.Items.ToString())完全错误:
ListBox.Items.ToString()返回的是控件本身的字符串标识(类似System.Windows.Forms.ListBox+ObjectCollection),并非当前要添加的学生条目字符串。- 正确的逻辑应该是先根据输入内容生成对应的学生条目信息,再去数据源
List<Student>或ListBox中做匹配检查。
另外,直接检查数据源List<Student>比检查ListBox更可靠,因为ListBox只是展示层,数据源才是真实数据的存储载体。
解决方案
方法1:检查数据源List<Student>(推荐)
直接遍历List<Student>,对比每个学生的属性是否与当前输入完全一致:
private void btnAdding_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txtName.Text) || string.IsNullOrWhiteSpace(txtLastName.Text) || string.IsNullOrWhiteSpace(txtClassroom.Text)) { MessageBox.Show("请填写所有文本框。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // 获取并格式化当前输入的学生信息 string name = txtName.Text.Trim(); string lastName = txtLastName.Text.Trim(); string classroom = txtClassroom.Text.Trim(); string date = dateDay.Value.ToString("dd.MM.yyyy"); // 遍历List检查重复 bool isDuplicate = false; foreach (var student in List) { if (student.Name == name && student.LastName == lastName && student.Classroom == classroom && student.DateDay == date) { isDuplicate = true; break; } } // 也可以用LINQ简化(需引用System.Linq) // bool isDuplicate = List.Any(s => s.Name == name && s.LastName == lastName && s.Classroom == classroom && s.DateDay == date); if (isDuplicate) { MessageBox.Show("该条目已存在。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { List.Add(new Student(name, lastName, classroom, date)); RefreshCheck(); } }
方法2:检查ListBox中的显示文本
如果一定要通过ListBox检查,需先生成当前输入对应的显示字符串,再对比ListBox中的项:
private void btnAdding_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txtName.Text) || string.IsNullOrWhiteSpace(txtLastName.Text) || string.IsNullOrWhiteSpace(txtClassroom.Text)) { MessageBox.Show("请填写所有文本框。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // 生成当前输入对应的显示字符串 string currentEntry = $"{txtName.Text.Trim()} {txtLastName.Text.Trim()} | {txtClassroom.Text.Trim()} | {dateDay.Value.ToString("dd.MM.yyyy")}"; // 遍历ListBox检查重复 bool isDuplicate = false; foreach (string item in ListBox.Items) { if (item == currentEntry) { isDuplicate = true; break; } } // 也可以用LINQ简化 // bool isDuplicate = ListBox.Items.Cast<string>().Any(item => item == currentEntry); if (isDuplicate) { MessageBox.Show("该条目已存在。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { List.Add(new Student(txtName.Text.Trim(), txtLastName.Text.Trim(), txtClassroom.Text.Trim(), dateDay.Value.ToString("dd.MM.yyyy"))); RefreshCheck(); } }
额外优化点
- 用
string.IsNullOrWhiteSpace()替代空字符串判断,能处理纯空格输入的情况。 - 对输入文本调用
Trim(),避免前后空格导致的“假重复”。 RefreshCheck()中,清空文本框的代码应放在循环外面,否则每次循环都会重复清空:
public void RefreshCheck() { ListBox.Items.Clear(); foreach (var student in List) { ListBox.Items.Add(student.StudentAdd()); } // 清空输入框的代码移至循环外 this.txtName.Clear(); this.txtLastName.Clear(); this.txtClassroom.Clear(); this.dateDay.Value = DateTime.Today; this.tabStudent.SelectedTab = this.tabCheck; }
内容的提问来源于stack exchange,提问作者im_anxii
相关产品推荐
相关产品推荐

