[英]Reset background colour of listview using TextChanged event after search
I have a textbox that I can use to search for items and subitems in a listview. 我有一个文本框,可用于在列表视图中搜索项目和子项目。 Once matches are found the BG colour of the items changes.
一旦找到匹配项,项目的BG颜色就会更改。 This works fine, but when I delete the entry from the textbox the items and subitems still remain highlighted until I enter another search.
效果很好,但是当我从文本框中删除条目时,项目和子项目仍保持突出显示状态,直到我输入另一个搜索。
I am not sure if it is the event that I am using or if it is a problem with my logic. 我不确定这是我正在使用的事件还是逻辑上的问题。 I want the items to be highlighted dynamically as the user types in the search but if they delete the entry I want the BG colour to change back to white.
我希望这些项随着用户在搜索中键入而动态突出显示,但是如果他们删除了该条目,我希望BG颜色变回白色。
private void txtSearchMenu_TextChanged(object sender, EventArgs e)
{
string searchVal = txtSearchMenu.Text.ToLower();
if (searchVal != "")
{
foreach (ListViewItem item in lvMenuItems.Items)
{
foreach (ListViewItem.ListViewSubItem subSearch in item.SubItems)
{
if (subSearch.Text.ToLower().Contains(searchVal) == true)
{
subSearch.BackColor = Color.MediumAquamarine;
}
else
{
subSearch.BackColor = Color.White;
}
}
item.UseItemStyleForSubItems = false;
}
}
}
As Sintar said: 正如辛塔尔所说:
private void txtSearchMenu_TextChanged(object sender, EventArgs e)
{
string searchVal = txtSearchMenu.Text.ToLower();
if (searchVal != "")
{
foreach (ListViewItem item in lvMenuItems.Items)
{
foreach (ListViewItem.ListViewSubItem subSearch in item.SubItems)
{
if (subSearch.Text.ToLower().Contains(searchVal) == true)
{
subSearch.BackColor = Color.MediumAquamarine;
}
else
{
subSearch.BackColor = Color.White;
}
}
item.UseItemStyleForSubItems = false;
}
}
else
{
foreach (ListViewItem item in lvMenuItems.Items)
{
foreach (ListViewItem.ListViewSubItem subSearch in item.SubItems)
{
subSearch.BackColor = Color.White;
}
}
}
}
when I delete the entry from the textbox the items and subitems still remain highlighted until I enter another search
当我从文本框中删除条目时,项目和子项目仍保持突出显示状态,直到我输入其他搜索
This is because you do nothing if textbox is blank. 这是因为如果文本框为空,则您什么也不做。
Move check for empty string inside foreach like this: 像这样将检查空字符串移到foreach中:
private void txtSearchMenu_TextChanged(object sender, EventArgs e)
{
string searchVal = txtSearchMenu.Text.ToLower();
foreach (ListViewItem item in lvMenuItems.Items)
{
foreach (ListViewItem.ListViewSubItem subSearch in item.SubItems)
{
// move condition here
if (searchVal != "" && subSearch.Text.ToLower().Contains(searchVal) == true)
{
subSearch.BackColor = Color.MediumAquamarine;
}
else
{
subSearch.BackColor = Color.White;
}
}
item.UseItemStyleForSubItems = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.