views:

97

answers:

3

I have two controls:

  1. list box
  2. text box

The list box binds its data from the database. What I want is: when I type any letter in the text box, the list box is filtered according to the text box (but just type any letter in the text box without clicking Enter or Tab or any other keyboard keys at the end). Always this does not work for me without Enter or Tab.

Is there any solution to my problem in ASP.NET?

When I type any letter in the text box the list box binds directly according to the text box.

I have listbox but in other pages I use gridview.

ex:

<asp:Label ID="lbl_englishTitle" runat="server" CssClass="subtitle" 
        Text="Searching by english title :"></asp:Label>
<asp:TextBox ID="txt_filterByEnglishTitle" runat="server" AutoPostBack="True" 
        ontextchanged="txt_filterByEnglishTitle_TextChanged"></asp:TextBox>
<asp:GridView ID="gv_viewPrograms" runat="server" 
        AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="programId"
        DataSourceID="ObjectDataSource2">
    <Columns>
        <asp:TemplateField HeaderText="#">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox7" runat="server" Height="20px"
                     ReadOnly="True"  Text='<%# Bind("programId") %>'
                     Width="100px"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label7" runat="server" 
                     Text='<%# Bind("programId") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="english title" >
            <EditItemTemplate>
                <asp:TextBox ID="TextBox8" runat="server" Height="20px" 
                     Text='<%# Bind("englishTitle") %>' Width="100px">
                </asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3"
                     runat="server" ControlToValidate="TextBox8"
                     ErrorMessage="the english title must be entered" 
                     Height="0px" Width="0px">*</asp:RequiredFieldValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label8" runat="server"
                     Text='<%# Bind("englishTitle") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="arabic title">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox9" runat="server" Height="20px" 
                     Text='<%# Bind("arabicTitle") %>' Width="100px">
                </asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label9" runat="server"
                     Text='<%# Bind("arabicTitle") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="number of terms">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox10" runat="server" Height="20px" 
                     Text='<%# Bind("numOfTerms") %>' Width="100px">
                </asp:TextBox>
                <asp:RangeValidator ID="RangeValidator3" runat="server" 
                     ControlToValidate="TextBox10" 
                     ErrorMessage="the item must be a number not _
                     greater than 10"
                     Height="0px" MaximumValue="10" MinimumValue="0"
                     Type="Integer" Width="0px">*</asp:RangeValidator>
                <asp:CompareValidator ID="CompareValidator5" runat="server" 
                     ControlToValidate="TextBox10"
                     ErrorMessage="the term must be a whole value" 
                     Height="0px" Operator="DataTypeCheck" Type="Integer"
                     Width="0px">*</asp:CompareValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label10" runat="server"
                     Text='<%# Bind("numOfTerms") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="credit hours">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox11" runat="server" Height="20px" 
                     Text='<%# Bind("creditHours") %>' Width="100px">
                </asp:TextBox>
                <asp:CompareValidator ID="CompareValidator6" runat="server" 
                     ControlToValidate="TextBox11" 
                     ErrorMessage="the credit hours must be a whole value"
                     Height="0px"Operator="DataTypeCheck" Type="Integer"
                     Width="0px">*</asp:CompareValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label11" runat="server"
                     Text='<%# Bind("creditHours") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="elective">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox12" runat="server" Height="20px" 
                     Text='<%# Bind("elective") %>' Width="100px">
                </asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label12" runat="server"
                     Text='<%# Bind("elective") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:CommandField HeaderText="Edit" ShowEditButton="True" />
        <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
    </Columns>
</asp:GridView>`

<asp:ObjectDataSource ID="ObjectDataSource2" runat="server" 
       SelectMethod="GetAllPrograms" DeleteMethod = "Delete"
       TypeName="Managers.Program" UpdateMethod="Save">
    <DeleteParameters>
        <asp:Parameter Name="programId" Type="Int32" />
    </DeleteParameters>
    <UpdateParameters>
        <asp:Parameter Name="numOfTerms" Type="Int32" />
        <asp:Parameter Name="creditHours" Type="Int32" />
        <asp:Parameter Name="elective" Type="String" />
        <asp:Parameter Name="paragraphId" Type="Int32" />
        <asp:Parameter Name="type" Type="Int16" />
        <asp:Parameter Name="FK_UnitId" Type="Int32" />
        <asp:Parameter Name="arabicTitle" Type="String" />
        <asp:Parameter Name="englishTitle" Type="String" />
        <asp:Parameter Name="programId" Type="Int32" />
    </UpdateParameters>
</asp:ObjectDataSource>`

My code behind code:

protected void txt_filterByEnglishTitle_TextChanged(object sender, EventArgs e)
    {
        gv_viewPrograms.DataSourceID = null;
        gv_viewPrograms.DataSourceID = ObjectDataSource3.ID;
        gv_viewPrograms.DataBind();
        chb_allPrograms.Checked = false;
       // txt_filterByEnglishTitle.Text = string.Empty;
        txt_filterByEnglishTitle.Focus();
    }
A: 

Try this:

Markup

<form id="form1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
    <asp:ListBox ID="ListBox1" runat="server" DataTextField="Name" DataValueField="Id"></asp:ListBox><br />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</form>

JavaScript

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

    var categories = [],
        elem = $('select[id$=ListBox1]');

    $(document).ready(function() {

        var addNewItem = function(o) {
            $('<option value="' + o.id + '">' + o.name + '</option>').appendTo(elem);
        }

        // Put the current list in a variable
        $('option', elem).each(function(idx, opt) {
            categories.push({
                id: $(opt).val(),
                name: $(opt).html()
            });
        });

        $('input[id$=TextBox1]').keyup(function(e) {

            // Clear current items
            $('option', elem).remove();

            if (this.value.match(/^[\w\s]+$/)) {
                var m = new RegExp(this.value, 'i');
                // Add new items
                for (var i = 0; i < categories.length; i++) {
                    if (categories[i].name.match(m))
                        addNewItem(categories[i]);
                }
            }
            else {
                for (var i = 0; i < categories.length; i++) {
                    addNewItem(categories[i]);
                }
            }

        });

    });

</script>

Code-Behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var categories = new[]
        {
            new { Id = 1, Name = "Desktop" },
            new { Id = 2, Name = "Laptop" },
            new { Id = 3, Name = "Printer" }
        };

        ListBox1.DataSource = categories;
        ListBox1.DataBind();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Write(ListBox1.SelectedIndex);
}
Mehdi Golchin
i wanna more general solution ,, what about if i have a grid view,,
i tried to put the text box and the list box or grid view on update panel and use text changed but always i need to finalize the letters typing by enter or tab.. i want as soon as i typed letters the gridview or listbox contents changed
does n't work with me.
A: 

What you're describing sounds an awful lot like the AutoCompleteExtender control from the ASP.NET AJAX Control Toolkit

check out a sample here

yorkrj
exactly it 's like this control ,,but i tried to use it , but it doesn't achieve the desired goal. i have two controls her.
A: 

<form id="form1" runat="server">
<table>
    <asp:ListBox ID="ListBox1" runat="server">
        <asp:ListItem Text="Abc" Value="Abc"></asp:ListItem>
        <asp:ListItem Text="Ab" Value="Ab"></asp:ListItem>
        <asp:ListItem Text="dbc" Value="dbc"></asp:ListItem>
        <asp:ListItem Text="dc" Value="dc"></asp:ListItem>
        <asp:ListItem Text="ebc" Value="ebc"></asp:ListItem>
        <asp:ListItem Text="ecf" Value="ecf"></asp:ListItem>
        <asp:ListItem Text="fgc" Value="fgc"></asp:ListItem>
        <asp:ListItem Text="fhg" Value="fhg"></asp:ListItem>
        <asp:ListItem Text="qwe" Value="qwe"></asp:ListItem>
    </asp:ListBox>
    <br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</table>
</form>
<script type="text/javascript">

    function DoListBoxFilter(listBoxSelector, filter, keys, values) {
        var list = $(listBoxSelector);
        var selectBase = '<option value="{0}">{1}</option>';

        list.empty();
        for (i = 0; i < values.length; ++i) { 

            var value = values[i];

            if (value == "" || value.toLowerCase().indexOf(filter.toLowerCase()) >= 0) {
                var temp = '<option value="'+keys[i]+'">'+value+'</option>' ;
                list.append(temp);
            }
        }
    }
    var keys=[];
    var values=[];

    var options=$('#<% = ListBox1.ClientID %> option');
    $.each(options, function (index, item) {
        keys.push(item.value);
        values.push(item.innerHTML);
    });

    $('#<% = TextBox1.ClientID %>').keyup(function() {

    var filter = $(this).val();

    DoListBoxFilter('#<% = ListBox1.ClientID %>', filter, keys, values);

});

and finally this answer my question ,, and if i could find another one for grid view this will be great,, thanks for all guys who help me..