简体   繁体   English

Asp.net 在文本末尾按下回车键时文本框返回空字符串 vb.net

[英]Asp.net textbox returns empty string when enter key is pressed at the end of text vb.net

I am very new to the world of aspx, web forms.我对 aspx 的世界很陌生,web forms。 But I am assigned to development of webform due to some circumstances.但由于某些情况,我被分配到 webform 的开发。 I am somehow struggling and surviving in this.我不知何故在这方面挣扎和生存。 I have a problem, may be if someone who is familiar with this, can help me understand is very much appreciable.我有一个问题,可能如果熟悉这个的人,可以帮助我理解是非常可观的。

Problem : I am created a search box functionality successfully in an aspx webform with codebehind as vb.问题:我在 aspx webform 中成功创建了一个搜索框功能,代码隐藏为 vb。 But the problem is, when I type some text in this search box and press enter, it reloads to initial state rather than show up the search results.但问题是,当我在此搜索框中键入一些文本并按 Enter 时,它会重新加载到初始 state 而不是显示搜索结果。 It works well when we just type text in it and do not press enter.当我们只在其中输入文本而不按 Enter 键时,它运行良好。 For every letter I type in the box, in displays with matching search results.对于我在框中键入的每个字母,都会显示匹配的搜索结果。 I just am wondering why is this not working if I type text and press enter at the end of text for example like google search.我只是想知道如果我输入文本并在文本末尾按回车键,例如谷歌搜索,为什么这不起作用。 For ex: I typed "test" in searchbox and press enter.例如:我在搜索框中输入了“test”,然后按 Enter。 Results appear perfect until I press enter key.结果看起来很完美,直到我按下回车键。 Once I press enter, it goes back to original state how ever it was.一旦我按下回车键,它就会回到原来的 state 原来的样子。

Investigation : I debugged it and found that when enter is pressed, the value in textbox becomes empty.调查:我调试了一下,发现当按回车时,文本框中的值变成了空。 I am unable to understand why is it getting empty even if text is present in text box.即使文本框中存在文本,我也无法理解为什么它会变空。 I tried onkeypress="return event.keyCode!=13" in我试过onkeypress="return event.keyCode!=13"

<asp:TextBox ID="SearchTextBox" runat="server" onkeypress="return event.keyCode:=13" CssClass="txt"></asp:TextBox> so as not to return empty value when enter is pressed. <asp:TextBox ID="SearchTextBox" runat="server" onkeypress="return event.keyCode:=13" CssClass="txt"></asp:TextBox>以免回车时返回空值。 But it did not work.但它没有用。

  • Dim searchkey As String
  • searchkey = SearchTextBox.Text . searchkey = SearchTextBox.Text

searchkey returns emtpy string and not "test" string. searchkey返回空字符串而不是“测试”字符串。 But why?但为什么? How can I overcome it?我怎样才能克服它?

Looking for: Is there a possibility that I can get the text value present in textbox when enter is pressed.寻找:当按下回车键时,是否有可能获得文本框中的文本值。

I appreciate your help and new learning for me感谢您对我的帮助和新的学习

Do not use onkeypress directly like this onkeypress="return event.keyCode!=13"不要像这样直接使用onkeypress onkeypress="return event.keyCode!=13"

create a common js file and use it anywhere you want, you can modify also in one js .创建一个通用的js文件并在任何你想要的地方使用它,你也可以在一个js中修改。

use common js file and create a function and use on your code via link like this <script src="~/js/common.js"></script>使用通用js文件并创建一个 function 并通过像这样的链接在您的代码上使用<script src="~/js/common.js"></script>

Here is the js code to prevent Enter key:这是防止Enter键的js代码:

function DisbleEntr(evt) {
if (evt.key == "Enter") {
    return false;
}}

and use in your code like this:并像这样在您的代码中使用:

<asp:TextBox ID="SearchTextBox" runat="server" onkeypress="return DisbleEntr(event);" CssClass="txt"></asp:TextBox>

hope this will help you希望对你有帮助

Well, first up, enter key tends to mean submit the page.好吧,首先,输入键往往意味着提交页面。

And ALSO note that a simple hit of the enter key will trigger the FIRST button found on that page!!!!还要注意,简单的回车键将触发该页面上的 FIRST 按钮!!!!

Say we have this simple grid and at the bottom I have a search box, and a search button.假设我们有这个简单的网格,底部有一个搜索框和一个搜索按钮。 Real simple, say like this:真的很简单,这样说:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataKeyNames="ID" CssClass="table table-striped" Width="50%">
    <Columns>
        <asp:BoundField DataField="FirstName" HeaderText="FirstName"     />
        <asp:BoundField DataField="LastName" HeaderText="LastName"       />
        <asp:BoundField DataField="HotelName" HeaderText="HotelName"     />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        <asp:TemplateField HeaderText="Edit Hotel" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Button ID="cmdEdit" runat="server" 
                    Text="Edit" CssClass="btn" OnClick="cmdEdit_Click" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<br />
<asp:Label ID="Label1" runat="server" Text="Search For Hotel" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:10px"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" 
    Text="Search" Style="margin-left:10px"
    CssClass="btn" />

Now, code to load above say this:现在,上面加载的代码是这样说的:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then
        LoadGrid()
        MyEditHotelC.ShowGrid(True)
    End If

End Sub

Sub LoadGrid()

    Dim rstData As DataTable
    rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName")
    GridView1.DataSource = rstData
    GridView1.DataBind()

End Sub

Note SUPER DUPER VERY VERY close - note in above, that on page load, I ALWAYS check for IsPostback.注意 SUPER DUPER 非常非常接近 - 请注意,在页面加载时,我总是检查 IsPostback。

Remember, for any button click or any post-back the page load event fires.请记住,对于任何按钮单击或任何回发,都会触发页面加载事件。 Including any button click - so code that setups up a grid, setups text box, or ANYTHING?包括任何按钮点击——所以设置网格、设置文本框或任何东西的代码? - you only want to run such code one time. - 你只想运行一次这样的代码。

We see/have about 5 posts a week here in which someone drops in a combo box, selects a value, and clicks a button - and then the selected value goes away!!!我们每周在这里看到/有大约 5 个帖子,其中有人掉入组合框中,选择一个值,然后单击一个按钮 - 然后所选值消失!

Why?为什么? Because they had code in the page load event to load up the combo box, and thus each and every time that setup code to load the combo box runs each time and blows out your combo box selection.因为他们在页面加载事件中有代码来加载组合框,因此每次加载组合框的设置代码每次都会运行并破坏您的组合框选择。

BIG HUGE LESSON:巨大的教训:

Quite much EVERY web page you build that has ANY setup code will thus have the above If NotPostBack code stub.因此,您构建的具有任何设置代码的每个 web 页面都将具有上述 If NotPostBack 代码存根。 I recon the last 100+ pages I built work this way.我以这种方式查看了我构建的最后 100 多个页面。

So, ALWAYS make sure you include that If Not Postback stub for page setup code, and NEVER forget to do this.因此,始终确保为页面设置代码包含 If Not Postback 存根,并且永远不要忘记这样做。

Ok, so we run the page and we have this:好的,所以我们运行页面,我们有这个:

在此处输入图像描述

Now the first rule:现在第一条规则:

When you hit a enter key inside of a text box, the FIRST button on the page we find will trigger.当您在文本框中按回车键时,我们找到的页面上的 FIRST 按钮将触发。

So, looking at above, what will happen?那么,看看上面,会发生什么?

Turns out the FIRST button on the page in tucked away in the GridView!!!!原来页面上的第一个按钮隐藏在 GridView 中!!!!

So, if I type in to search box, and hit enter key, then this button will be clicked on:所以,如果我在搜索框中输入,然后按回车键,那么这个按钮将被点击:

在此处输入图像描述

Surprise!!!!惊喜!!!!

Now, why is this most of the time never a issue?现在,为什么这在大多数时候都不是问题?

Well, in most cases, you don't have a lot of buttons and I can/could fix above, by simple moving the search box, and button to the top, say like this:好吧,在大多数情况下,您没有很多按钮,我可以/可以通过简单地将搜索框和按钮移动到顶部来修复上面的问题,如下所示:

在此处输入图像描述

So, it turns out by luck, we find in most cases this is not a issue.因此,幸运的是,我们发现在大多数情况下这不是问题。

And a slick easy way to fix this issue?以及解决此问题的简单方法?

Well, drop in a button at the VERY top of the page - set style = "display:none" (to hide the button, and this issue is fixed - all without any special code).好吧,在页面的最顶部放一个按钮 - set style = "display:none" (隐藏按钮,这个问题已经解决 - 没有任何特殊代码)。

eg this:例如这个:

<form id="form1" runat="server">

    <asp:Button ID="catchEnter" runat="server" Text="Button" 
        OnClientClick="return false" style="display:none"/>

So, VERY first control on page.所以,页面上的第一个控件。

next up:接下来:

So, VERY much keep the above in mind.所以,请记住以上几点。

Next issue:下一期:

For every letter I type in the box, in displays with matching search results.对于我在框中键入的每个字母,都会显示匹配的搜索结果。

Ok, so you have some type of auto-complete code.好的,所以你有某种类型的自动完成代码。 That is a HUGE issue - and there are about 20+ libraries and examples floating around on the internet.这是一个巨大的问题——互联网上大约有 20 多个库和示例。 You don't mention what code library you adopted (maybe the one from jQuery.UI, maybe the one from the ajaxtoolkit - but boatloads of systems exist).您没有提及您采用的代码库(可能来自 jQuery.UI 的代码库,可能来自 ajaxtoolkit 的代码库 - 但存在大量系统)。

Or MAYBE you rolled your own?或者也许你自己推出了? I actually VERY high recommend the ajaxtoolkit, since it has a really nice autocomplete extender - and it uses ajax calls without postbacks for this setup.我实际上非常推荐 ajaxtoolkit,因为它有一个非常好的自动完成扩展器——并且它使用 ajax 调用而无需回发此设置。

Your issue is thus above and in summary:因此,您的问题在上面和总结中:

The text box has some library code attached - gets setup in page load - but you failed to adopt and is the IsPostBack = false test.文本框附加了一些库代码 - 在页面加载中设置 - 但您未能采用并且是 IsPostBack = false 测试。

The enter key not being trapped - and thus above - first button ANYWHERE in the page - even those tucked away in a grid view or anywhere else is thus causing a page post-back.回车键没有被困住 - 因此在页面上的第一个按钮的任何地方 - 即使是那些隐藏在网格视图或其他任何地方的按钮,也会导致页面回发。

You not shared if your auto complete setup DOES a post-back, but again if it does, then that's often the issue.如果您的自动完成设置确实进行了回发,则您没有分享,但如果确实如此,那么这通常是问题所在。

So to prevent enter key clicking on first button, you can add the above "trick" and drop in a hidden button, and one that when clicked on does not cause a post-back due to enter key.因此,为了防止回车键点击第一个按钮,您可以添加上面的“技巧”并放入一个隐藏按钮,当点击该按钮时不会因为回车键而导致回发。

Since I have the ajax tool kit installed?既然我安装了 ajax 工具包?

I can do this:我可以做这个:

在此处输入图像描述

I choose Add extender for that text box, and choose this:我为该文本框选择添加扩展器,然后选择:

在此处输入图像描述

So, it puts in this markup for me:所以,它为我添加了这个标记:

            <ajaxToolkit:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" 
                BehaviorID="txtSearch_AutoComplete" 
                DelimiterCharacters="" 
                ServiceMethod="SearchCustomers"
                MinimumPrefixLength="1" 
                CompletionInterval="100" 
                EnableCaching="false"
                CompletionSetCount="40"
                TargetControlID="txtSearch">
            </ajaxToolkit:AutoCompleteExtender>

Nice about above?上面好看吗? I can set how many chars before search.我可以在搜索之前设置多少个字符。 I can set the timign to update etc. And I not had to write one line of js code either!!!我可以设置时间来更新等。而且我也不必写一行js代码!!!

So the above looks like this now所以上面现在看起来像这样

在此处输入图像描述

So, the only part I had to setup and write was the code behind for this search.因此,我必须设置和编写的唯一部分是此搜索背后的代码。

That was this:那是这样的:

<WebMethod()>
Public Shared Function SearchCustomers(ByVal prefixText As String, ByVal count As Integer) As List(Of String)

    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = My.Settings.TEST4
        Using cmd As SqlCommand = New SqlCommand()
            cmd.CommandText = "select HotelName from tblHotels where HotelName like @SearchText + '%'
                               ORDER BY HotelName"
            cmd.Parameters.AddWithValue("@SearchText", prefixText)
            cmd.Connection = conn
            conn.Open()
            Dim customers As List(Of String) = New List(Of String)()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    customers.Add(sdr("HotelName").ToString())
                End While
            End Using
            conn.Close()

            Return customers
        End Using
    End Using
End Function

But, all the rest?但是,所有的 rest? No extra code.没有额外的代码。

So, I would consider to adopt a stadnard library (jquery.UI maybe, or the above ajaxtoolkit).所以,我会考虑采用一个标准库(可能是 jquery.UI,或者上面的 ajaxtoolkit)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM