完成asp.net中的另一个函数后,C#代码跳转到未调用的函数

时间:2016-07-07 07:25:59

标签: c# asp.net

背景

我的网页上有一个用户可以提交身份证号码的地方。他们可以将ID输入文本框,也可以从下拉列表中选择使用频繁的ID。由于这两个输入源基本上做同样的事情,我对它们使用相同的回调函数。此函数中有检查以查看发件人是文本框还是下拉列表(以及相应的验证检查)。

问题:

我从这个功能中得到了一些非常奇怪的行为。当调用此函数并且发送者是下拉列表时,一切都按预期工作。但是,当调用此函数并且发件人是文本框时,在退出函数之前,一切似乎都很好。一旦函数退出,控制会立即跳转到另一个我在该函数内没有调用过的无关函数。当我测试它和调试器时,它会在Web上跳转。它总是跳到相同的功能。此函数本身就是页面上其他位置的按钮的回调函数(仅在用户明确按下按钮时才会调用)。

我不知道为什么会这样做,也无法弄清楚出了什么问题。

相关代码

注意:如果重要的话,文本框和下拉列表都在GridView的EditItemTemplate中。

<asp:TextBox ID="TextBoxCQ" runat="server" BackColor="#ffcccc" Text="Enter CQ here" onclick="$(this).val('');" OnTextChanged="cq_Selected_In_Edit"></asp:TextBox>
<asp:DropDownList ID="AssociatedCQList" runat="server" BackColor="#ffcccc" AppendDataBoundItems="True" Font-Size="Smaller" AutoPostBack="True" DataSourceID="SqlDataSource_CQList" DataTextField="cqdetail" DataValueField="cqID" OnSelectedIndexChanged="cq_Selected_In_Edit">
                    <asp:ListItem Selected="True" Enabled="true" Value="Select from list of CQ's">Select from list of CQ's </asp:ListItem>
                </asp:DropDownList>

代码背后:

    protected void cq_Selected_In_Edit(object sender, EventArgs e)
    {
        object type = sender.GetType();
        string name = ((System.Reflection.MemberInfo)(type)).Name;
        bool isTextbox = (name == "TextBox"); // to be used throughout the function
        GridViewRow Row;
        string text;
        if (isTextbox) // it's the textbox calling
        {
            Row = (GridViewRow)((System.Web.UI.WebControls.TextBox)(sender)).NamingContainer;
            text = ((System.Web.UI.WebControls.TextBox)(sender)).Text;
        }
        else // it's the dropdown calling
        {
            Row = (GridViewRow)((System.Web.UI.WebControls.DropDownList)(sender)).NamingContainer;
            text = ((System.Web.UI.WebControls.ListControl)(sender)).Text;
        }
        // do more processing, etc etc
    }

2 个答案:

答案 0 :(得分:1)

控件的IDTextBoxQC,您需要将其与TextBox进行比较才能找到正确的对象。由于2个字符串不相等,因此评估为false。

由于您希望始终使用代码,请将其更改为

bool isTextbox = (name.Contains("TextBox"));

正如函数所示,它正在检查字符串是否包含文本TextBox

答案 1 :(得分:0)

我仍然不知道导致这究竟是什么,尽管它似乎与文本框具有想要按下按钮的亲和力这一事实有关。

解决问题的方法是将文本框放在面板中,然后让面板按下一个隐藏按钮,该按钮调用代码隐藏功能(当然,后面的代码中也需要稍作修改)。一个简单的实现如下所示:

<asp:Panel runat="server" DefaultButton="btnSearch">
    <asp:TextBox id="txtSearch" runat="server" />
    <asp:Button id="btnSearch" runat="server" text="Start search" />
</asp:Panel>

代码来源:How can I fire a Button Click event when Enter Key is pressed based on what textbox has focus?