如何在按键弹起时使文本框回发?

26

我有一个文本框,在 OnTextChanged 事件中更改下拉列表的内容。但是,这个事件似乎在文本框失去焦点时才触发。我该如何在 keypress 或 keyup 事件上实现这一功能?

以下是我的代码示例:

<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>

在代码后端,我在页面加载时绑定下拉列表。Code_TextChanged事件只是重新绑定下拉列表。我希望这个事件在每次按键时都会发生,而不是在文本框失去焦点时才发生。

我最近继承了这段代码,但对我来说,这不是理想的方法,但时间限制阻止我重写为Web服務方法。

我尝试使用jQuery将"keyup"事件绑定到文本框,以匹配"change"事件,但这只在第一次按键时起作用。

4个回答

45

这将解决您的问题,逻辑与Kyle建议的解决方案相同。

看看这个。

<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>

代码后端如下所示...

 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");
    }

我已经添加了额外的文本框以查看更改情况,删除该文本框。


1
当UpdatePanel刷新时,文本框会失去焦点。同样的情况也会发生在这里。 - Russ Bradberry
4
只需使用此解决方案删除 AutoPostBack="true",它就应该能正常工作。 - rick schott
Rick的评论是正确的,移除AutoPostBack后它将会顺利工作。 - Tom Halladay
__doPostBack() 中,我在 Code.ClientID 上遇到了“文字量过多”的错误。 - vapcguy
@vapcguy 使用双引号 " 而不是单引号,因为它只期望在单引号之间有一个字符。 - Madmenyo

4
这里介绍一种使用JavaScript、更新面板、GridView、SqlDataSource和文本框的简单方法。当你输入内容时,它会搜索表格并显示结果。简短明了,无需后台代码。
<%@ 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>


1
我将使用JavaScript技巧来触发OnTextChanged事件,调用模糊函数,然后重新聚焦输入文本(如果您有多个输入文本,则从两个输入文本中切换焦点)。
我已在IE和Firefox中进行了测试。
JavaScript代码:
function reFocus(id) 
    {
        document.getElementById(id).blur();
        document.getElementById(id).focus();
    }

aspx代码

<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>

这个 C# 函数 "GridProdotto_SelectedIndexChanging" 从数据库中检索数据并构建网格。


0

我尝试过这个方法,但它只在第一次按键时有效。之后,文本框失去焦点,每次按键都无法触发事件。正如您所看到的,与您推荐的帖子相反,我的文本框不在更新面板中,但仍然会失去焦点。 - Russ Bradberry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接