【问题标题】:Windows form c# Search button with textbox带有文本框的 Windows 窗体 c# 搜索按钮
【发布时间】:2021-08-18 06:55:53
【问题描述】:

在创建带有文本框和验证框的搜索按钮方面需要帮助。

  1. 我无法让我的 CustomerArray 显示在带有制表符空格的一行上。
  2. 我无法打开一个验证框,上面写着“没有输入客户,请输入一个”)。当文本框中没有输入客户时,请按下搜索按钮。

这就是我目前所拥有的:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchName = txtSearch.Text;

    for (int i = 0; i < CustomerDB.Count; i++)
    {
        string item = Convert.ToString(CustomerDB[i].GetCustomer());
        //MessageBox.Show(item);
        if (item.Contains(searchName))
        {
            index = i;
            //MessageBox.Show("index" + i);
        }
    }
    lstCustomerDB.Items.Clear();

    if (index < 0)
    {
        MessageBox.Show("Customer not found, please try again");

    }
    else
    {

        MessageBox.Show("Customer found");
        string Customer = Convert.ToString(CustomerDB[index].GetCustomer());
        string[] CustomerArray = Customer.Split('\t');
        lstCustomerDB.Items.Clear();
        for (int i = 0; i < CustomerArray.Length; i++)
        {

            lstCustomerDB.Items.Add(CustomerArray[i]);

        }


    }
}

任何帮助都非常感谢!

【问题讨论】:

  • Convert.ToString(CustomerDB[i].GetCustomer()); 将返回默认的"YourNamespace.Customer",除非您的Customer 类已覆盖ToString(); 方法。
  • ListBoxes 不是在单行上显示多列信息的最佳控件。您应该查看 DataGridView.. 然后 GetCustomer 似乎返回一个字符串,其中包含由制表符分隔的信息。这看起来很复杂,而且不是很面向对象。相反,您应该返回 Customer 类的实例并对其进行操作以在 DataGridView 中显示信息
  • 抱歉,需要来自列表框。不过谢谢!
  • index 变量需要在搜索循环之前重置。例如:index = -1; 高于行 for (int i = 0; i &lt; CustomerDB.Count; i++)

标签: c# windows forms winforms button


【解决方案1】:

1. 我没有得到 GetCustomer() 的确切返回内容以及您使用 Split() 的原因。如果你希望你的结果在一行中,你可以使用CustomerDB[index].GetCustomer().Join("\t")

2. 您正在尝试在此处使用带有 string 项目的 string[].Contains() 方法

string item = Convert.ToString(CustomerDB[i].GetCustomer());
        //MessageBox.Show(item);
        if (item.Contains(searchName))
        {
            index = i;
            //MessageBox.Show("index" + i);
        }

改用Customer Object,如Customer item = CustomerDB[i].GetCustomer()

Customer item = CustomerDB[i].GetCustomer();
        //MessageBox.Show(item);
        if (item.Contains(searchName))
        {
            index = i;
            //MessageBox.Show("index" + i);
        }
  • 您可以使用中断;如果您完成查找索引,则退出 foreach:
Customer item = CustomerDB[i].GetCustomer();
        //MessageBox.Show(item);
        if (item.Contains(searchName))
        {
            index = i;
            //MessageBox.Show("index" + i);
            break;
        }

熊猫中士

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 2012-01-23
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多