Windows窗体按钮代码



我正在尝试为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;
}
}

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

使用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;
}

最新更新