There is a ListBox with text. How to make it so that when we write a word in TextBox, these words are highlighted in ListBox?

  • wrap html tags? - Gorets
  • A simpler solution is available !!! - IGOR

2 answers 2

I'll try to recoup :)

My version with ListView:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Test_Project { public partial class Form1 : Form { public List<Char> letters = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToList(); public List<String> words = new List<string>(); Random random = new Random(); String word; public Form1() { InitializeComponent(); getRandomWords(); } private void textBox1_TextChanged(object sender, EventArgs e) { ListViewItem item = listView1.FindItemWithText(textBox1.Text); int index = listView1.Items.IndexOf(item); if (index != -1) { for (int i = 0; i < listView1.Items.Count; i++) listView1.Items[i].BackColor = Color.White; listView1.Items[index].BackColor = Color.Crimson; } else for (int i = 0; i < listView1.Items.Count; i++) listView1.Items[i].BackColor = Color.White; } private void button1_Click(object sender, EventArgs e) { getRandomWords(); } protected void getRandomWords() { listView1.Items.Clear(); words.Clear(); for (int j = 0; j < 10; j++) { word = ""; for (int i = 0; i < 4; i++) { word += letters[random.Next(0, letters.Count)].ToString(); } words.Add(word); } foreach (var i in words) { listView1.Items.Add(i); } } } } 
  • It remains a little garbage from the old program, I will explain briefly: On the form there is a ListView, TextBox and there is a button. When you start the program / press the button, 10 random words are generated (stupidly a set of letters). Next, look at the task. - Olter

Add keystroke handler and set ListBox values ​​depending on TextBox values

 private void formX_KeyDown(object sender, KeyEventArgs e) { int index = listboxX.FindString(textboxX.Text); if (index != -1) listboxX.SetSelected(index, true); } 
  • one
    Damn, did not have time to write: D Plus - Olter
  • This I have done for a long time !!! This method selects the position where the word is located !! And I just need the word to be highlighted !! - IGOR
  • one
    @IGOR, in this case, you better not use a ListBox, but a ListView. Then you can enter your value in this way, for example, in listView1.Items [index] .BackColor. For ListBox, you can do this too, but then you need to overload listBox1_DrawItem and put DrawMode in OwnerDrawFixed, it is difficult. - Olter