我有一个带有gridview控件的ASP.NET页面,其中有一个CommandButton列,其中delete和select命令处于活动状态。

按Enter键会导致gridview中的第一个命令按钮触发,从而删除一行。我不希望这种情况发生。我可以更改gridview控件,使其不再按Enter键吗?

屏幕上还有一个文本框和按钮。他们不需要响应击中输入,但您必须能够填写文本框。目前我们弹出一个确认对话框以防止意外删除,但我们需要比这更好的东西。

这是gridview的标记,因为你可以看到它在asp.net更新面板内(我忘了提,抱歉):(我遗漏了大多数列和格式化)

<asp:UpdatePanel ID="upContent" runat="server" UpdateMode="Conditional">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnFilter" />
            <asp:AsyncPostBackTrigger ControlID="btnEdit" EventName="Click" />
        </Triggers>
        <ContentTemplate>
            <div id="CodeGrid" class="Grid">
                <asp:GridView   ID="dgCode" runat="server">
                    <Columns>
                        <asp:CommandField SelectImageUrl="~/Images/Select.GIF"
                                            ShowSelectButton="True"
                                            ButtonType="Image"
                                            CancelText=""
                                            EditText=""
                                            InsertText=""
                                            NewText=""
                                            UpdateText=""
                                            DeleteImageUrl="~/Images/Delete.GIF"
                                            ShowDeleteButton="True" />
                        <asp:BoundField DataField="Id"  HeaderText="ID" Visible="False" />
                    </Columns>
                </asp:GridView>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
有帮助吗?

解决方案

此解决方案阻止整个页面上的回车键

禁用输入密钥

其他提示

每隔一段时间我就会遇到像这样的愚蠢问题......但通常我只是实施快速黑客攻击,继续前进:)

myGridView.Attributes.Add("onkeydown", "if(event.keyCode==13)return false;");

这样的事情应该有用。

在PreRender事件中,您可以切换

Private Sub gvSerials_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvSerials.PreRender
    If gvSerials.EditIndex < 0 'READ ONLY MODE
        'Enables the form submit during Read mode on my 'search' submit button
        Me.bnSearch.UseSubmitBehavior = True
    Else 'EDIT MODE
        'disables the form submit during edit mode, this allows the APPLY/Update button to be activated after Enter Key is pressed (which really is creating a form submit)
        Me.bnSearch.UseSubmitBehavior = False
    End If

在Page_Load中,将焦点设置在文本框上。

这是一个很好的 jQuery 方式。此函数将自动将keydown事件处理程序添加到页面上的所有TextBox。通过使用不同的选择器,您可以将其控制到更多或更少的粒度级别:

//jQuery document ready function – fires when document structure loads
$(document).ready(function() {

   //Find all input controls of type text and bind the given
   //function to them
   $(":text").keydown(function(e) {
      if (e.keyCode == 13) {
          return false;
       }
   });

});

这将使所有文本框忽略Enter键,并且具有自动应用于您可能添加到页面的任何新HTML或ASP.Net控件(或者可能由ASP.Net生成)的优势。

对于其他有同样问题的人,这段代码没有阻止事件被触发,这对我有用:

if (window.event.keyCode == 13) {    
    event.returnValue=false;     
    event.cancel = true;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top