Dec 16, 2009

Search Option in ListView Control

private ListView textListView = new ListView();
private TextBox searchBox = new TextBox();
private void InitializeTextSearchListView()
{
searchBox.Location = new Point(10, 60);
textListView.Scrollable = true;
textListView.Width = 80;
textListView.Height = 50;

// Set the View to list to use the FindItemWithText method.
textListView.View = View.List;

// Populate the ListViewWithItems
textListView.Items.AddRange(new ListViewItem[]{
new ListViewItem("Amy Alberts"),
new ListViewItem("Amy Recker"),
new ListViewItem("Erin Hagens"),
new ListViewItem("Barry Johnson"),
new ListViewItem("Jay Hamlin"),
new ListViewItem("Brian Valentine"),
new ListViewItem("Brian Welker"),
new ListViewItem("Daniel Weisman") });

// Handle the TextChanged to get the text for our search.
searchBox.TextChanged += new EventHandler(searchBox_TextChanged);

// Add the controls to the form.
this.Controls.Add(textListView);
this.Controls.Add(searchBox);

}

private void searchBox_TextChanged(object sender, EventArgs e)
{
// Call FindItemWithText with the contents of the textbox.
ListViewItem foundItem =
textListView.FindItemWithText(searchBox.Text, false, 0, true);
if (foundItem != null)
{
textListView.TopItem = foundItem;

}
}

No comments: