【问题标题】:Windows Forms Button codesWindows 窗体按钮代码
【发布时间】:2021-05-26 03:23:02
【问题描述】:

我正在尝试为 C# 表单中的搜索按钮创建/编码。

这是我目前所拥有的:

private void btnSearch_Click(object sender, EventArgs e)
{
    for (int i = 0; i < lstCustomerDB.Items.Count; i++)
    {
        string item = lstCustomerDB.Items[i].ToString();
        if (item.Contains(txtSearch.Text)) 
        {
            index = 1;
        }
    }
    lstCustomerDB.Items.Clear();

    if (index < 0)
    {
      `enter code here`  MessageBox.Show("Item not found.");
        txtSearch.Text = String.Empty;
    }
    else
    {
        lstCustomerDB.SelectedIndex = index;
    }
}

任何帮助将不胜感激!谢谢!

【问题讨论】:

  • 抱歉忘记提及它还必须经过验证和索引。对不起!

标签: c# winforms button


【解决方案1】:

使用 LINQ:

private void Search()
{
    //Grab the first item that matches (or null if not found)
    var firstMatch = lstCustomerDB.Items.Cast<string>()
            .FirstOrDefault(x => x.Contains(txtSearch.Text));
    if (firstMatch != null)
    {
        lstCustomerDB.SelectedItem = firstMatch;
    }
    else
    {
        MessageBox.Show("Item not found.");
        txtSearch.Text = String.Empty;
    }
}

修改你的代码:

int index = -1;
for (int i = 0; i < lstCustomerDB.Items.Count; i++)
{
     string item = lstCustomerDB.Items[i].ToString();
     if (item.Contains(txtSearch.Text)) 
     {
         index = i;
         lstCustomerDB.SelectedIndex = index;
         break;
     }
}
if (index < 0)
{
     MessageBox.Show("Item not found.");
     txtSearch.Text = String.Empty;
}

【讨论】:

  • 谢谢,但是一旦我添加了休息时间,它仍然不起作用。不过谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-06-05
  • 2020-09-21
  • 2012-08-08
  • 2010-09-16
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多