在C#中搜索单词 [英] Searching word in c#

查看:68
本文介绍了在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 the TextBox. Since, TextBox can not show multiple names, ComboBox can be used for this purpose, by appropriately setting the DataSource, 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);
		}

	}
}


这篇关于在C#中搜索单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆