【问题标题】:How do you insert data from one form into a listbox in another form while checking for unique values?如何在检查唯一值的同时将数据从一个表单插入到另一个表单的列表框中?
【发布时间】:2021-07-08 00:53:08
【问题描述】:

我有两个表单,HomeForm 和 AddForm。 AddForm 有五个文本框,registrationNumber、carMake、carModel、carYear 和 carHireCost。我已经创建了按预期将信息发送到列表框的代码。这看起来像这样:

        HomeForm f1 = (HomeForm)Application.OpenForms["HomeForm"];
            f1.UpdateListBox(registrationNumber.Text + "     " + carMake.Text + "     " + carModel.Text + "     " + carYear.Text + "     " + carHireCost.Text);
            this.Hide();

我希望能够检查注册号是否已经存在。如果是这样,它将引发错误并且不会更新列表框。如果它是唯一的注册号,它会将其添加到列表中,以及其他详细信息。在尝试更新列表之前如何编写检查唯一性的语句?

例如:

if ("check registration exists = does exist"){
 MessageBox.Show("Registration Number already exists.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}else{
  HomeForm f1 = (HomeForm)Application.OpenForms["HomeForm"];
            f1.UpdateListBox(registrationNumber.Text + "     " + carMake.Text + "     " + carModel.Text + "     " + carYear.Text + "     " + carHireCost.Text);
            this.Hide();
}

编辑 我的主表单中有一个更新列表框的方法,其中 vehicleList 是列表框的名称。它看起来像这样:

  public void UpdateListBox(string lstValue)
        {
            vehicleList.Items.Add(lstValue);
        }

【问题讨论】:

  • 这可以通过多种方式完成。您可以在 HomeForm 中有一个方法可以检查列表框是否具有传入的注册号,您可以有第三个类将注册号添加到您可以检查的集合中,等等。
  • 代码f1.UpdateListBox在做什么?您应该显示此代码。您应该edit您的问题提供有关代码当前如何将项目添加到ListBox. 的更多详细信息
  • 使用表单实例。查看我的两个表单项目:stackoverflow.com/questions/34975508/…
  • 我已经用更新列表框的主表单中的方法更新了我的问题

标签: c# winforms listbox


【解决方案1】:

既然您要检查“注册号”是否已经在列表中,那么就目前而言,您有两个选择……

  1. 从传入的变量lstValue中解析出注册号,然后循环遍历每个列表项,查看该项是否包含注册号。

或者

  1. 将注册号作为单独的变量传递。然后循环遍历列表中的每一项,查看该项是否包含注册号。

使用第二种方法可能看起来像……

public void UpdateListBox(string regNumber, string lstValue) {
  foreach (string item in vehicleList.Items) {
    if (item.Contains(regNumber)) {
      MessageBox.Show("Registration number: " + regNumber + " already exist in the list! Item not added!");
      return;
    }
  }
  vehicleList.Items.Add(regNumber + "      " + lstValue);
}

【讨论】:

  • 我试试看
【解决方案2】:

您可以在ListBoxItems 集合上调用Contains 方法来检查ListBox 是否已经包含该条目。

public void UpdateListBox(string lstValue)
{
    if(vehicleList.Items.Contains(lstValue)
    {
        return; // already in list, do not add again
    }
    vehicleList.Items.Add(lstValue);
}

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多