在onkeypress事件中对数据列表项进行排序 [英] sorting datalist items on onkeypress event
问题描述
我有一个数据列表,上面有一个文本框.
而且我想做的是在文本框中输入一个字符时,只有与该字符相对应的项才应b填充到数据列表中.所有过程都应在文本框的onkeypress事件上进行
注意:数据列表中只有900个名称列表.
i have a datalist above which i have a textbox.
and what i want to do is as i enter a character in textbox, only items corresponding to that char should b filled in datalist.and all process should be on onkeypress event of textbox
NOTE: there is only 900 names list in datalist.
推荐答案
您必须使用自动回发或(更快的)ajax,如下所示:
You have to use autopostback, or (faster) ajax like this:
<asp:TextBox runat="server" ID="txtFilter" autocomplete="off" ></asp:TextBox>
<asp:LinkButton runat="server" ID="lbFilter" onclick="FilterDropdown" Text="filter" style="visibility:hidden;"></asp:LinkButton>
<asp:ScriptManager runat="server" ID="scrMang"></asp:ScriptManager>
<asp:UpdatePanel ID="updSelction" runat="server">
<ContentTemplate>
<asp:ListBox runat="server" ID="ddl" ></asp:ListBox>
</ContentTemplate>
<Triggers >
<asp:AsyncPostBackTrigger ControlID="lbFilter" />
</Triggers>
</asp:UpdatePanel>
public partial class _Default : System.Web.UI.Page
{
string[] Names = {"Andreas",
"Benjamin",
"Caroline",
"Daniel",
"Emil",
"Franziska",
"Gustav",
"Hans"
};
protected void Page_Load(object sender, EventArgs e)
{
txtFilter.Attributes.Add("onkeyup", "__doPostBack('" + lbFilter.UniqueID + "','');");
if(!IsPostBack) {
foreach(var name in Names) {
ddl.Items.Add(name);
}
}
}
protected void FilterDropdown(object sender, EventArgs e) {
ddl.Items.Clear();
foreach(var name in Names) {
if(name.ToLower().Contains(txtFilter.Text.ToLower())) {
ddl.Items.Add(name);
}
}
txtFilter.Focus();
if(ddl.Items.Count >0)
ddl.Items[0].Selected = true;
}
}
如果您知道如何使用LINQ,则可以只编写几行代码并获得所需的结果:
If you know how to use LINQ then you can write only a couple of lines of code and achieve the desired outcome:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string search = textBox1.Text;
listBox1.DataSource = (from l in list where l.Contains(search) select l).ToList();
}
列表"只是在构造函数中定义并填充的简单字符串列表.尝试一下并尝试一下.
干杯...
如果您还不了解LINQ,这是一个不错的开始, http://msdn.microsoft .com/en-us/netframework/aa904594 [ ^ ]
使用
"list" is just a simple list of strings defined in the constructor and populated. Try it and hack around with it.
Cheers...
here is a good start for LINQ if you don''t already know it, http://msdn.microsoft.com/en-us/netframework/aa904594[^]
use
l.StartsWith(search)
而不是
l.Contains(search)
进行野外搜索. StartsWith搜索更准确的字符串开头.
which does a wild search. StartsWith searches for the beginning of the string which is more accurate.
这篇关于在onkeypress事件中对数据列表项进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!