#c# #winforms #button
Вопрос:
Я пытаюсь создать/код для кнопки поиска в формах 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;
}
}
За любую помощь буду благодарен! Спасибо!
Комментарии:
1. Извините, забыл упомянуть, что он также должен быть проверен и проиндексирован. Прости!
Ответ №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;
}
Комментарии:
1. Спасибо, но все равно не работает, как только я добавлю в перерыве. Но Спасибо!