Saturday, 6 April 2013

Filter the Gridview as you type in the Textbox

In this post I will explain how to filter the Gridview synchronously while typing into the Textbox.

First of all create a Textbox, Gridview and a Button. here I have added a button to be clicked while we enter the text into the textbox. Add an Update panel and put Gridview into it to prevent the postback full page. set the trigger on the serverclick event of the button, so it will be updated while the button click even fires.

This is the code to create UI. 

<asp:ScriptManager ID="ScriptManager" runat="server">
    </asp:ScriptManager>
    <div>
        <button id="btnSearch" type="button" runat="server" class="SeachClick" onserverclick="btnSearch_Click"
            style="display: none;">
        </button>
        <asp:TextBox ID="txtSearch" runat="server" onkeyup="Search(this);" ClientIDMode="Static"></asp:TextBox>
        <br />
        <asp:UpdatePanel ID="upl" runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="serverclick" />
            </Triggers>
            <ContentTemplate>            
                <asp:GridView ID="gvImage" runat="server" AutoGenerateColumns="false" ClientIDMode="Static">
                    <Columns>
                        <asp:TemplateField HeaderText="Sr No." HeaderStyle-HorizontalAlign="Center">
                            <HeaderStyle Width="100" />
                            <ItemStyle HorizontalAlign="Center" />
                            <ItemTemplate>
                                <asp:Label ID="lblID" CssClass="lblID" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Image Name" HeaderStyle-HorizontalAlign="Center">
                            <HeaderStyle Width="200" />
                            <ItemStyle HorizontalAlign="Center" />
                            <ItemTemplate>
                                <asp:Label ID="lblImageName" CssClass="lblImageName" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Image" HeaderStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:Label ID="lblImage" CssClass="lblImage" runat="server" Text='<%# Eval("Image") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>


Now add the script to click the Button on text change of Textbox.

<script type="text/javascript">
        function Search(ctrl) {
            if ($(ctrl).val() != null)
                $(".SeachClick").click();
            $(ctrl).focus();
        }
    </script>


Now add the following code to your code behind page.

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {              
                SqlDataAdapter da = new SqlDataAdapter("select * from ImageData", con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                gvImage.DataSource = ds;
                gvImage.DataBind();
            }
        }
     
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string search = txtSearch.Text;
            SqlDataAdapter da = new SqlDataAdapter("select * from ImageData where ImageName like '%" + search + "%'", con);
            DataSet ds = new DataSet();
            da.Fill(ds);              
            gvImage.DataSource = ds;
            gvImage.DataBind();
        }


Script to create table is

USE [DATABASE1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ImageData](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ImageName] [varchar](50) NULL,
[Image] [varchar](100) NULL,
 CONSTRAINT [PK_ImageData] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

In table I have added path of Image in Image column.

If you have any doubt put comment......

3 comments:

  1. Can you please simply tell me the code on textbox textchange event.
    i am having some code bt it is not properly working-

    Imports System.Data
    Imports System.Data.OleDb
    Imports System.Data.SqlClient


    Public Class Form1

    Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Dim con As New SqlConnection("Data Source=SKY-PC\SQLEXPRESS;Initial Catalog=myapp;Integrated Security=True")
    Dim dvFilter As DataView = Nothing

    If TypeOf DataGridView1.DataSource Is DataView Then
    dvFilter = CType(DataGridView1.DataSource, DataView)
    ElseIf TypeOf DataGridView1.DataSource Is DataTable Then
    dvFilter = CType(DataGridView1.DataSource, DataTable).DefaultView

    End If
    If TextBox1.TextLength > 0 Then
    dvFilter.RowFilter = ("select * from tt where name like '*" & TextBox1.Text & "*'")
    Else
    dvFilter.RowFilter = ""
    End If
    DataGridView1.DataSource = dvFilter

    '==================

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    'TODO: This line of code loads data into the 'MyappDataSet.tt' table. You can move, or remove it, as needed.
    Me.TtTableAdapter.Fill(Me.MyappDataSet1.tt)
    End Sub
    End Class

    ReplyDelete
    Replies
    1. Hi Prateek,
      Sorry for late reply...
      Here I have simply clicked a button on the textchnage of textbox. so you can add following javascript,
      in Script tag add this function

      function Search(ctrl) {
      if ($(ctrl).val() != null)
      $(".SeachClick").click();
      $(ctrl).focus();
      }


      and call this function using onkeyup like onkeyup="Search(this);"

      now do whatever you like to do on this button click.
      I hope this will work for you.

      Delete
  2. $(ctrl).focus(); isnt working after calling the function

    ReplyDelete