Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter GridView on TextBox's KeyPress event from code behind

I have a TextBox with KeyPressed event and I want to filter GridView on that event using jquery/javascript.

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

Note that GridView binding code is from .CS file:

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

I don't know how it will work? It should bind on key pressing of TextBox.


Edit: I have find a solution server site OnTextChanged event of TextBox which bind the GridView after pressing Enter instead of pressing a key.

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

I don't want it with OnTextChanged event but I think it would work on keypressed event using JavaScript or jQuery so I don't know how to do?


Update: I have tried below jQuery code to key pressed in textbox but its also not working.

$(document).ready(function () {

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

Note: GridView and TextBox both are inside 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>
like image 333
youpilat13 Avatar asked Sep 24 '17 06:09

youpilat13


5 Answers

I hope this solution would help even though its a bit different than the actual method you used. Do the following carefully and if any change is needed do not hesitate to comment. You need first to use the jquery's CDN library as following in the section:(just in case people did not use it yet)

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

Create A Button inside the update panel (the same one containing the gridview) and make it invisible using css not from visible attribute used in asp.net like this:

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

The Button is used to trigger server side code to be able to bind the gridview (pagemethods or webmethods does not allow usage of instance members since it uses shared functions.

Place the Textbox Outside the update panel and remove the autopostback=true(in case you are using it).

At the end of the body use the following code:

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

        });
    });

</script>

the jquery code is used to bind the keyup event ( similiar to the key pressed but after it the key is clicked) to a certain function where you can do whatever code you want. However, $('#InvisButton').click() is used to trigger the server side code of the button with the said ID or its click event handler. which in my case i used simple code, in your case maybe you could use it like this:

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

Note:

Sorry if any function mistakes occur, i tried to convert from vb.net to C# and changing IDs.

like image 58
JKOU Avatar answered Nov 18 '22 21:11

JKOU


Used this '#<%=txtSearch.ClientID%>' syntax for asp controls IDs in jQuery instead of '#txtSearch'.

  • Add this script:

    <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>
    
  • And in .Aspx code:

    <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>
    
  • And in code-behind:

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

    enter image description here

    enter image description here

like image 25
stefan Avatar answered Sep 19 '22 12:09

stefan


You can use a WebMethod Function to call your filter data Like this

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

Call it from .aspx page

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

For More Reference: https://www.aspsnippets.com/demos/685/

like image 28
Negi Rox Avatar answered Nov 18 '22 22:11

Negi Rox


You can use OnTextChanged instead on OnKeyPressed and also set AutoPostBack="True"on textbox and you can do whatever you want in code behind file it work properly.

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

C# Code

On Text Changed

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

Edit

On 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
}
like image 4
Muhammad Asad Avatar answered Nov 18 '22 22:11

Muhammad Asad


Text changed will be working only when you use AutoPostBack = true

AutoPostBack = true permits control to post back to the server. It is associated with an Event.

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

Edit:

On 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();
    }
}
like image 3
Tummala Krishna Kishore Avatar answered Nov 18 '22 22:11

Tummala Krishna Kishore