在C#中搜索单词
有没有人可以帮助我在c#Windows窗体中进行搜索.
e.x
我有一个名称为:
的列表框
迈克
安东尼奥
马克
杰姬
布鲁斯
阿隆索
...
...
...
因此,如果我插入一个文本框,然后仅写第一个字符,则所有以该字符开头的名称都将显示...
does any one can help me with searching in c# windows form.
e.x
I have a listbox with name:
Mike
Antonio
Mark
Jackie
Bruss
Alonso
...
...
...
so If I insert a text box and then when a just write the first character then all names that start with that character to show...
提到当写入第一个字符时,所有以该字符开头的名称都应显示在TextBox
中.由于TextBox
不能显示多个名称,因此可以通过适当地设置DataSource, DropDownStyle, AutoCompleteSource and AutoCompleteMode
属性,如下所示来使用ComboBox
:
In the question it is mentioned that when first character is written then all names starting with that character shall be shown in theTextBox
. Since,TextBox
can not show multiple names,ComboBox
can be used for this purpose, by appropriately setting theDataSource, DropDownStyle, AutoCompleteSource and AutoCompleteMode
properties as shown below:
ListBox listBox1 = new ListBox();
List<string> names = new List<string>() {
"Mike", "Antonio","Mark",
"Jackie", "Bruss","Alonso"
};
BindingSource bindingSource1 = new BindingSource();
bindingSource1.DataSource = names;
ComboBox comboBox1 = new ComboBox();
comboBox1.Dock = DockStyle.Bottom;
comboBox1.DataSource = bindingSource1;
comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
listBox1.Dock = DockStyle.Fill;
listBox1.DataSource = bindingSource1;
Controls.Add(comboBox1);
Controls.Add(listBox1);
要运行上述示例,请在Visual Studio中创建一个Windows Forms项目,在设计器中双击Form1,这将打开代码文件,将以上代码粘贴到Form1的Load事件中并运行该应用程序.
To run the above sample, create a Windows Forms project in Visual Studio, double click on Form1 in the designer, which opens the code file, paste the above code in the Load event of Form1 and run the application.
然后使用此
then use this
private string[] ValArray;
private void Form1_Load(object sender, System.EventArgs e)
{
// set value for ValArray
ListBox1.Items.AddRange(ValArray);
}
private void TextBox1_TextChanged(System.Object sender, System.EventArgs e)
{
if (TextBox1.Text == string.Empty){
ListBox1.Items.AddRange(ValArray);
return;
}
ListBox1.Items.Clear();
foreach (string item in ValArray) {
if (item.StartsWith(TextBox1.Text)) {
ListBox1.Items.Add(item);
}
}
}