簡體   English   中英

從代碼隱藏的TextBox的KeyPress事件中過濾GridView

[英]Filter GridView on TextBox's KeyPress event from code behind

我有一個帶有KeyPressed事件的TextBox,我想使用jquery / javascript在該事件上過濾GridView。

<asp:TextBox ID="txtSearch" runat="server" OnKeyPressed="txtSearch_KeyPressed()">
</asp:TextBox>

<script>
  function txtSearch_KeyPressed()
  {
      // gvBanquet is an ID of GridView and SearchBanquet method returns a DataTable
      gvBanquet.DataSource = DLBqt.SearchBanquet(txtSearch.Text.Trim());
      gvBanquet.DataBind();
  }
</script>

請注意,GridView綁定代碼來自.CS文件:

gvBanquet.DataSource = DLBqt.SearchBanquet(txtSearch.Text.Trim());
gvBanquet.DataBind();

我不知道它會如何起作用? 它應該在TextBox的按鍵上綁定。


編輯:我找到了TextBox的解決方案服務器站點OnTextChanged事件,它在按Enter后綁定GridView而不是按鍵。

<asp:TextBox ID="txtSearch" runat="server" OnTextChanged="txtSearch_TextChanged" 
    AutoPostBack="True" ></asp:TextBox>

protected void txtSearch_TextChanged(object sender, EventArgs e)
{
    gvBanquet.DataSource = DLBqt.SearchBanquet(txtSearch.Text.Trim());
    gvBanquet.DataBind();
}

我不希望它與OnTextChanged事件,但我認為它將使用JavaScriptjQuery的 keypressed事件,所以我不知道該怎么辦?


更新:我已嘗試下面的jQuery代碼按鍵在文本框中按,但它也無法正常工作。

$(document).ready(function () {

    $('#txtSearch').on("keyup", function () {
        // could bind bind GridView here??
        e.preventDefault();
    })
})

注意: GridView和TextBox都在UpdatePanel中。

 <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <div class="col-lg-4" style="padding-right:0px"> <asp:TextBox ID="txtSearch" Width="100%" CssClass="form-control" placeholder="Search..." runat="server"></asp:TextBox> <input id="inpHide" type="hidden" runat="server" /> </div> </div> <!-- /.col-lg-12 --> <div class="col-lg-12 table-responsive"> <asp:GridView ID="gvBanquet" CssClass="table table-striped table-bordered table-hover" runat="server" AutoGenerateColumns="false" OnRowCommand="gvBanquet_RowCommand" AllowPaging="True" PageSize="5" EmptyDataText="No record found!" OnPageIndexChanging="gvBanquet_PageIndexChanging" ShowHeaderWhenEmpty="true" > <Columns> <asp:TemplateField HeaderText="Banquet Name"> <ItemTemplate> <asp:Label ID="lblID" runat="server" Visible="false" Text='<% #Eval("bqtID") %>'></asp:Label> <asp:Label ID="lblName" runat="server" Text='<% #Eval("bqtName") %>' ></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="User Name"> <ItemTemplate> <asp:Label ID="lblUserName" runat="server" Text='<% #Eval("bqtUserName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Type"> <ItemTemplate> <asp:Label ID="lblType" runat="server" Text='<% #Eval("bqtType") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Capacity"> <ItemTemplate> <asp:Label ID="lblCapacity" runat="server" Text='<% #Eval("bqtCapacity") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Password"> <ItemTemplate> <asp:Label ID="lblPassword" runat="server" Text='<% #Eval("bqtPassword") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Email"> <ItemTemplate> <asp:Label ID="lblEmail" runat="server" Text='<% #Eval("bqtEmail") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Phone"> <ItemTemplate> <asp:Label ID="lblPhone" runat="server" Text='<% #Eval("bqtPhone") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Cell No."> <ItemTemplate> <asp:Label ID="lblContactNo" runat="server" Text='<% #Eval("bqtContactNo") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Location"> <ItemTemplate> <asp:Label ID="lblLocation" runat="server" Text='<% #Eval("bqtLocation") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate> <center>Events</center> </HeaderTemplate> <ItemTemplate> <asp:Button ID="btnStatus" runat="server" CssClass="btn btn-primary btn-sm" CommandName="Status" Text='<%# Eval("bqtStatus") %>' /> <asp:Button ID="btnEdiit" runat="server" CssClass="btn btn-danger btn-sm" CommandName="EditRow" Text="Edit" /> <asp:Button ID="btnDelete" runat="server" CssClass="btn btn-danger btn-sm" CommandName="DeleteRow" Text="DELETE" /> </ItemTemplate> </asp:TemplateField> </Columns> <HeaderStyle BackColor="#5cb85c" BorderColor="#4CAE4C" ForeColor="White"></HeaderStyle> <PagerStyle CssClass="pagination-ys" /> </asp:GridView> <asp:Label ID="lblNoRecords" runat="server" Text="No Record Found!"></asp:Label> </div> <!-- /.col-lg-12 --> </ContentTemplate> </asp:UpdatePanel> 

我希望這個解決方案有所幫助,即使它與您使用的實際方法略有不同。 請仔細執行以下操作,如果需要進行任何更改,請不要猶豫。 首先需要使用jquery的CDN庫,如下所示:(以防萬一人們還沒有使用它)

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

在更新面板(包含gridview的同一個)中創建一個Button,並使用css使其不可見,而不是使用asp.net中使用的可見屬性,如下所示:

 <asp:button ID="InvisButton" runat="server" style="display:none;" OnClick="InvisButton_Click" />

Button用於觸發服務器端代碼以便能夠綁定gridview(pagemethods或webmethods不允許使用實例成員,因為它使用共享功能。

將文本框放在更新面板外部並刪除autopostback = true(如果您使用它)。

在正文的末尾使用以下代碼:

<script type="text/javascript">
    $(document).ready(function () {
        $('#<%=txtSearch.ClientID%>').bind('keyup', function () {
            alert($('#<%=txtSearch.ClientID%>').val());
            $('#<%=InvisButton.ClientID%>').click();

        });
    });

</script>

jquery代碼用於綁定keyup事件(類似於按下的鍵,但在點擊鍵之后)到某個函數,在那里你可以做任何你想要的代碼。 但是,$('#InvisButton')。click()用於觸發具有所述ID或其click事件處理程序的按鈕的服務器端代碼。 在我的情況下,我使用簡單的代碼,在你的情況下,也許你可以像這樣使用它:

protected void InvisButton_Click(object sender, EventArgs e)
{
// place your wanted code here
gvBanquet.DataSource = DLBqt.SearchBanquet(txtSearch.Text.Trim());
gvBanquet.DataBind();
}

注意:

對不起,如果發生任何功能錯誤,我試圖從vb.net轉換為C#並更改ID。

您可以在OnKeyPressed上使用OnTextChanged ,並在文本框中設置AutoPostBack="True" ,您可以在文件后面的代碼中執行任何操作,它可以正常工作。

   <asp:TextBox ID="txtSearch" runat="server" OnTextChanged="txtSearch_Changed()" 
    AutoPostBack="True"> </asp:TextBox>

C#代碼

在文本更改

public void txtSearch_Changed(object sender, EventArgs e)
{
    gvBanquet.DataSource = DLBqt.SearchBanquet(txtSearch.Text.Trim());
    gvBanquet.DataBind();
}

編輯

在EveryKeyPress上

ASPX

      <asp:TextBox ID="txtSearch" runat="server"  
    AutoPostBack="True"> </asp:TextBox>
 <script>
    $("#<%=txtSearch.ClientID%>").keypress(function () {
        console.log("Handler for .keypress() called.");
        __doPostBack(this.name, 'OnKeyPress');
    });
</script>

C#

protected void Page_Load(object sender, EventArgs e){
    var ctrlName = Request.Params[Page.postEventSourceID];
    var args = Request.Params[Page.postEventArgumentID];

    if(ctrlName == txtSearch.UniqueID && args == "OnKeyPress"){
        MyTextBox_OnKeyPress(ctrlName, args);
    }
}

private void MyTextBox_OnKeyPress(string ctrlName, string args){
    //your code goes here
}

您可以使用WebMethod函數來調用您的過濾器數據

private static int PageSize = 5;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindDummyRow();
    }
}

private void BindDummyRow()
{
    DataTable dummy = new DataTable();
    dummy.Columns.Add("CustomerID");
    dummy.Columns.Add("ContactName");
    dummy.Columns.Add("City");
    dummy.Rows.Add();
    gvCustomers.DataSource = dummy;
    gvCustomers.DataBind();
}

[WebMethod]
public static string GetCustomers(string searchTerm, int pageIndex)
{
    string query = "[GetCustomers_Pager]";
    SqlCommand cmd = new SqlCommand(query);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@SearchTerm", searchTerm);
    cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
    cmd.Parameters.AddWithValue("@PageSize", PageSize);
    cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
    return GetData(cmd, pageIndex).GetXml();
}

private static DataSet GetData(SqlCommand cmd, int pageIndex)
{
    string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds, "Customers");
                DataTable dt = new DataTable("Pager");
                dt.Columns.Add("PageIndex");
                dt.Columns.Add("PageSize");
                dt.Columns.Add("RecordCount");
                dt.Rows.Add();
                dt.Rows[0]["PageIndex"] = pageIndex;
                dt.Rows[0]["PageSize"] = PageSize;
                dt.Rows[0]["RecordCount"] = cmd.Parameters["@RecordCount"].Value;
                ds.Tables.Add(dt);
                return ds;
            }
        }
    }
}

從.aspx頁面調用它

     function GetCustomers(pageIndex) {
        $.ajax({
            type: "POST",
            url: "CS.aspx/GetCustomers",
            data: '{searchTerm: "' + SearchTerm() + '", pageIndex: ' + pageIndex + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    }

更多參考: https//www.aspsnippets.com/demos/685/

只有在使用AutoPostBack = true時,更改的文本才會起作用

AutoPostBack = true允許控件回發到服務器。 它與事件相關聯。

<asp:TextBox ID="txtSearch" runat="server" AutoPostBack = "true"  OnTextChanged="txtSearch_TextChanged" >
</asp:TextBox>

protected void txtSearch_TextChanged(object sender, EventArgs e)
{
    gvBanquet.DataSource = DLBqt.SearchBanquet(txtSearch.Text.Trim());
    gvBanquet.DataBind();
}

編輯:

在EveryKeyPress上

ASPX

 <asp:textbox id="MyTextBox" runat="server" 
onkeypress="__doPostBack(this.name,'OnKeyPress');" ></asp:textbox>

C#

protected void Page_Load(object sender, EventArgs e){
    var ctrlName = Request.Params[Page.postEventSourceID];
    var args = Request.Params[Page.postEventArgumentID];

    if(args == "OnKeyPress"){
        gvBanquet.DataSource = DLBqt.SearchBanquet(txtSearch.Text.Trim());
         gvBanquet.DataBind();
    }
}

你缺少id選擇器,用這個替換你的示例代碼

$(document).ready(function () {

$('#txtSearch').on("keyup", function () {
    // could bind bind GridView here??
    e.preventDefault();
})

})

  1. 替換: OnKeyPressed="txtSearch_KeyPressed()"使用: AutoPostBack="true"
  2. 在設計模式下查看aspx代碼(您可以在其中看到您的用戶界面。)
  3. 雙擊文本框。
  4. 在自動創建的方法中添加這兩行進行綁定:

     gvBanquet.DataSource = DLBqt.SearchBanquet(txtSearch.Text.Trim()); gvBanquet.DataBind(); 

基本上,每次將一個字符插入到文本框中時,都會發生一個PostBack,並且將由visual studio自動創建新方法(如果您粘貼了代碼,則會綁定數據)。

*如果每次綁定到數據庫,您的代碼將占用內存並且非常慢(而是使用Angularjs加載)。

你無法從jQuery過濾文本框,感染.ASPX控件無法從jQuery / Javascript調用.CS代碼。 您可以通過將UpdatePanel添加到.ASPX代碼中然后添加標記AutopostBack=True來實現它。

在jQuery中使用這個'#<%=txtSearch.ClientID%>'語法來代替'#txtSearch'

  • 添加此腳本:

     <script src="../Scripts/jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#<%=txtSearch.ClientID%>').bind('keyup', function (e) { $('#<%=btnInvisible.ClientID%>').click(); }); }); </script> 
  • .Aspx代碼中:

     <asp:TextBox ID="txtSearch" placeholder="Search..." runat="server"></asp:TextBox> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Button ID="btnInvisible" runat="server" style="display: none" OnClick="btnInvisible_Click" /> // Place GridView here </ContentTemplate> </asp:UpdatePanel> 
  • 在代碼隱藏中:

     protected void btnInvisible_Click(object sender, EventArgs e) { gvBanquet.DataSource = DLBqt.SearchBanquet(txtSearch.Text.Trim()); gvBanquet.DataBind(); } 
  • 結果是:

    在此輸入圖像描述

    在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM