English 中文(简体)
How do I make a Textbox Postback on KeyUp?
原标题:

I have a Textbox that changes the content of a dropdown in the OnTextChanged event. This event seems to fire when the textbox loses focus. How do I make this happen on the keypress or keyup event?

Here is an example of my code

<asp:TextBox ID="Code" runat="server" AutoPostBack="true" OnTextChanged="Code_TextChanged">                

<asp:UpdatePanel ID="Update" runat="server">
    <ContentTemplate>
        <asp:DropDownList runat="server" ID="DateList" />             
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Code" />
    </Triggers>
</asp:UpdatePanel>

So in the codebehind, I bind the dropdown on page load. The Code_TextChanged event just rebinds the dropdown. I would like this to happen on each keypress rather than when the textbox loses focus.

I inherited this code recently and this is not the ideal method of doing this for me, but time limitations prevent me from rewriting this in a web servicy method.

I have tried using jQuery to bind the "keyup" event to match the "change" event for the textbox, but this only works on the first key pressed.

最佳回答

This will solve your problem. Logic is same as the solution suggested by Kyle.

Have a look at this.

<head runat="server">
<title></title>
<script type="text/javascript">
    function RefreshUpdatePanel() {
        __doPostBack( <%= Code.ClientID %> ,   );
    };
</script>

    <asp:TextBox ID="Code" runat="server" onkeyup="RefreshUpdatePanel();" AutoPostBack="true" OnTextChanged="Code_TextChanged"></asp:TextBox>
    <asp:UpdatePanel ID="Update" runat="server">
        <ContentTemplate>
            <asp:DropDownList runat="server" ID="DateList" />
            <asp:TextBox runat="server" ID="CurrentTime" ></asp:TextBox>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Code" />
        </Triggers>
    </asp:UpdatePanel>

Code behind goes like this...

 protected void Code_TextChanged(object sender, EventArgs e)
    {
        //Adding current time (minutes and seconds) into dropdownlist
        DateList.Items.Insert(0, new ListItem(DateTime.Now.ToString("mm:ss")));

        //Setting current time (minutes and seconds) into textbox
        CurrentTime.Text = DateTime.Now.ToString("mm:ss");
    }

I have added additional textbox to see change in action, do remove the textbox.

问题回答

Here is a simple way to do it with javascript, an update panel, gridview, sqldatasource and a textbox. As you type it searches the table and displays the results. Short and sweet, no code behind.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test3.aspx.vb" Inherits="test3" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
 <script type="text/javascript">
     function runPostback() {
         document.forms["form1"].submit();
         document.getElementById("TextBox1").focus();
     }
     function getFocus(){
         var text = document.getElementById("TextBox1");
         if (text != null && text.value.length > 0) {
             if (text.createTextRange) {
                 var FieldRange = text.createTextRange();
                 FieldRange.moveStart( character , text.value.length); 
                 FieldRange.collapse();
            FieldRange.select(); } }
}

function SetDelay() {
    setTimeout("runPostback()", 200);
}




 </script>
</head>
<body onload="getFocus()">
<form id="form1" runat="server">
<div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="TextBox1" />
        </Triggers>
        <ContentTemplate>
            <asp:TextBox ID="TextBox1" onkeyup="SetDelay();" runat="server"></asp:TextBox>
            <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:purchasing2ConnectionString %>"
                SelectCommand="SELECT [name] FROM [vendors] WHERE ([name] LIKE  @name +  % )">
                <SelectParameters>
                    <asp:ControlParameter ControlID="TextBox1" Name="name" PropertyName="Text" Type="String" />
                </SelectParameters>
            </asp:SqlDataSource>
        </ContentTemplate>
    </asp:UpdatePanel>
</div>
</form>

I use a javascript trick for trigger a OnTextChanged event, i call a blur function and than re-focus the input text (or, if you have many input text, switch focus from two input text)

I have test it in IE and Firefox.

javascript code:

function reFocus(id) 
    {
        document.getElementById(id).blur();
        document.getElementById(id).focus();
    }

aspx code

<asp:TextBox ID="txtProdottoLike" runat="server"
                ontextchanged="txtProdottoLike_TextChanged"
                onKeyUp="reFocus(this.id);" 
                AutoPostBack="True">
</asp:TextBox>

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>                
<asp:UpdatePanel ID="Update" runat="server">
    <ContentTemplate>
        <asp:GridView ID="GridProdotto" runat="server" AllowPaging="False" 
                AllowSorting="False" ForeColor="#333333" GridLines="None"
            OnSelectedIndexChanging="GridProdotto_SelectedIndexChanging"
            Visible="True"  Width="100%" Height="100%" AutoGenerateColumns="False">
            <RowStyle BackColor="WhiteSmoke" Font-Size="11px" />
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:BoundField DataField="Prodotto">
                    <ItemStyle Width="80px" HorizontalAlign="Left" />
                    <HeaderStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:BoundField DataField="Descrizione">
                    <ItemStyle HorizontalAlign="Left" />
                    <HeaderStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:CommandField SelectText="Seleziona" ShowSelectButton="True" ItemStyle-HorizontalAlign="Right"></asp:CommandField>
            </Columns>
        </asp:GridView>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="txtProdottoLike" />
    </Triggers>
</asp:UpdatePanel>

The c# function "GridProdotto_SelectedIndexChanging" retrive data from database and build the grid.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签