Tuesday, 11 February 2014

Search GridView records (data) on TextBox KeyPress using jQuery in ASP.Net

In order to search GridView records (data) on TextBox KeyPress event, I am making use of jQuery QuickSearch Plugin which dynamically searches the GridView cells and filters out the unwanted rows and displays only the records (data) that matches the input search term.
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView with BoundField columns. I have specified OnDataBound event of the GridView to dynamically add a row with TextBoxes for searching records in each column of GridView.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="100" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" />
    </Columns>
</asp:GridView>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
 
Binding the GridView control
I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event.
  C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
       dt.Rows.Add(1, "Rama devi","India");
        dt.Rows.Add(2, "Jason steve", "America");
        dt.Rows.Add(3, "Rajitha Ganesh", "India");
        dt.Rows.Add(4, "Kshatriya Dev", "Australia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
Adding a Row of TextBox for Searching Data
Inside the OnDataBound event handler, I have created a new GridView Header Row with a TextBox in its each Cell and then added this row to the GridView. These TextBoxes will be used to search the respective GridView column on TextBox KeyPress event.
You will notice that the CssClass property is set for each TextBox with value search_textbox, this has been done to apply the jQuery QuickSearch plugin client side using the jQuery CSS class selector.
C#
protected void OnDataBound(object sender, EventArgs e)
{
    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
    for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        TableHeaderCell cell = new TableHeaderCell();
        TextBox txtSearch = new TextBox();
        txtSearch.Attributes["placeholder"] = GridView1.Columns[i].HeaderText;
        txtSearch.CssClass = "search_textbox";
        cell.Controls.Add(txtSearch);
        row.Controls.Add(cell);
    }
    GridView1.HeaderRow.Parent.Controls.AddAt(1, row);
}
  
Applying the jQuery QuickSearch Plugin
The jQuery QuickSearch Plugin is applied using the jQuery CSS class selector for each TextBox inside the GridView Header Row.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="quicksearch.js"></script>
<script type="text/javascript">
    $(function () {
        $('.search_textbox').each(function (i) {
            $(this).quicksearch("[id*=GridView1] tr:not(:has(th))", {
                'testQuery': function (query, txt, row) {
                    return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
                }
            });
        });
    });
</script>
 
 
 

Display GridView Selected Row data in TextBox outside GridView in ASP.Net

Inside the GridView SelectedIndexChanged event handler, the TextBoxes outside GridView will be populated using the data fetched from the GridView’s Selected Row.
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView and TextBoxes which will be used to display the data from the Selected Row. For the GridView, I have specified the OnSelectedIndexChanged event handler.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:TemplateField HeaderText="Country">
            <ItemTemplate>
                <asp:Label ID="lblCountry" Text='<%# Eval("Country") %>' runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<br />
<table cellpadding="0" cellspacing="0">
    <tr>
        <td style="width: 100px">
            Id
        </td>
        <td>
            <asp:TextBox ID="txtId" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Name
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server" />
        </td>
    </tr>
        <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Country
        </td>
        <td>
            <asp:TextBox ID="txtCountry" runat="server" />
        </td>
    </tr>
</table>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
  
Binding the GridView control
I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "Rama devi","India");
        dt.Rows.Add(2, "Jason steve", "America");
        dt.Rows.Add(3, "Rajitha Ganesh", "India");
        dt.Rows.Add(4, "Kshatriya Dev", "Australia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
 
Display GridView Selected Row data in TextBox outside GridView in ASP.Net using the SelectedIndexChanged event
Inside the SelectedIndexChanged event handler of the GridView control, the values from the BoundField and TemplateField columns are extracted and displayed in the respective TextBoxes placed outside the GridView control.
C#
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = GridView1.SelectedRow;
    txtId.Text = row.Cells[0].Text;
    txtName.Text = row.Cells[1].Text;
    txtCountry.Text = (row.FindControl("lblCountry") as Label).Text;
}
 
ID
Name
Country

1
Rama devi
India
Select
2
Jason Steve
America
Select
3
Rajitha Ganesh
India
Select
4
Kshatriya Dev
Australia
Select
 
 

Validate GridView with CheckBox (at least one checked) using JavaScript in ASP.Net

Validation of CheckBoxes inside GridView is performed using ASP.Net CustomValidator with a client side JavaScript validation function.
In this article I will explain how to validate CheckBoxes inside GridView and perform at least one checked validation using JavaScript in ASP.Net.
Validation of CheckBoxes inside GridView is performed using ASP.Net CustomValidator with a client side JavaScript validation function.
HTML Markup
The HTML Markup consists of an ASP.Net GridView with three columns and the first column being a TemplateField with a CheckBox placed inside it.
Below the GridView there’s a CustomValidator and a Button control.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="CheckBox1" runat="server" Text='<%# Eval("Id") %>' />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select at least one record."
    ClientValidationFunction="Validate" ForeColor="Red"></asp:CustomValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
   
Namespaces
You will need to import the following namespaces.
using System.Data;
Binding the GridView control
I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event.
  protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
 
CustomValidator JavaScript Validation function
Below is the JavaScript function that gets executed when the CustomValidator is triggered on the button click. It first gets the GridView and its internal CheckBoxes and then a loop is executed to check whether the CheckBoxes are checked or unchecked.
If a CheckBox is found checked then the IsValid variable is set to true else it is set to false.
<script type="text/javascript">
    function Validate(sender, args) {
        var gridView = document.getElementById("<%=GridView1.ClientID %>");
        var checkBoxes = gridView.getElementsByTagName("input");
        for (var i = 0; i < checkBoxes.length; i++) {
            if (checkBoxes[i].type == "checkbox" && checkBoxes[i].checked) {
                args.IsValid = true;
                return;
            }
        }
        args.IsValid = false;
    }
</script>