我有一个TextBox
可以搜索ListView
中的所有内容。我希望有一个ComboBox
,允许用户根据搜索条件在ListView
内“全部显示”,“显示匹配”和“显示不匹配”。
private void SearchBtn_Click(object sender, EventArgs e)
{
int count = 0, searchStartIndex = selectedIndexPos = 0;
// Clear previously selected indices
listView.SelectedIndices.Clear();
string target = searchTextBox.Text;
// Search for item with text from the search text box, including subItems, from searchStartIndex, not a prefixSearch
ListViewItem item = listView.FindItemWithText(target, true, searchStartIndex, false);
/*----------------------------------------------------------------------------------------------------*
* While the search results in an item found continue searching. *
*----------------------------------------------------------------------------------------------------*/
while (item != null)
{
count++;
// Update progressBar
progressBar.Value = (int)((float)searchStartIndex / listView.VirtualListSize * 100);
ListView.SelectedIndexCollection indexes = listView.SelectedIndices;
if (!indexes.Contains(item.Index))
{
listView.SelectedIndices.Add(item.Index);
}
/*----------------------------------------------------------------------------------------------------*
* Set the start index to the index after the last found, if valid start index search for next item.*
*----------------------------------------------------------------------------------------------------*/
if ((searchStartIndex = item.Index + 1) < listView.VirtualListSize)
{
item = listView.FindItemWithText(searchTextBox.Text, true, searchStartIndex, false);
// count++;
}
else
{
item = null;
}
}
if (listView.SelectedIndices.Count == 0)
{
MessageBox.Show("Find item with text \"" + searchTextBox.Text + "\" has no result.");
}
else
{
RefilterListView();
listView.EnsureVisible(listView.SelectedIndices[0]);
}
}
我希望将我的项目放在“组合框”中,以帮助过滤“列表视图”。 “显示全部”应显示“ ListView”的所有内容以及搜索到的项目,“显示匹配”应仅显示搜索到的项目,删除所有与搜索不匹配的内容,“显示不匹配”应显示所有内容'ListView'中与搜索到的内容不匹配的内容。
答案 0 :(得分:0)
我不能完全按照您的情况做。但我希望我能意识到。我的意思是,这只是解决方案。您可以根据自己的情况对其进行自定义。
首先,在您的BindingSource
上放一个Form
并将其绑定到您的数据:
bindingSource1.DataSource = data;
然后将您的ListView
(实际上是DataGridView
)绑定到BindingSource
:
dataGridView1.DataSource = bindingSource1;
然后像这样定义enum
:
public enum Something
{
ShowMatch = 1,
ShowNonMatch = 2
}
现在,在您的ComboBox
上放一个Form
并为其添加选项:
comboBox1.Items.Add("Show All");
comboBox1.Items.Add("ShowMatch");
comboBox1.Items.Add("ShowNonMatch");
comboBox1.SelectedIndex = 0;
之后,您可以在SelectedIndexChanged
中捕获所选项目:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
bindingSource1.Filter = null;
else
bindingSource1.Filter = $"Name = '{comboBox1.SelectedItem.ToString()}'";
}