In this article I will explain how to filter GridView rows based on ListBox’s multiple selections in ASP.Net with C# and VB.Net.
The GridView rows will be filtered on ListBox SelectedIndexChanged event.
 
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
 
Concept
The ListBox displays some Countries and the GridView will be populated with records from the Customers table of the Northwind database.
When the ListBox’s item is selected or unselected the GridView records will be filtered based on the selected Countries.
If none of the items of the ListBox are selected then the GridView will display all records.
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView and a ListBox control. The ListBox control has been assigned an OnSelectedIndexChanged event handler and the SelectionMode property has been set to allow multiple selections.
<asp:ListBox ID="lstCountries" runat="server" AutoPostBack="true" SelectionMode = "Multiple" OnSelectedIndexChanged="Country_Selected">
    <asp:ListItem Text="Argentina" Value="Argentina"></asp:ListItem>
    <asp:ListItem Text="Austria" Value="Austria"></asp:ListItem>
    <asp:ListItem Text="Belgium" Value="Belgium"></asp:ListItem>
    <asp:ListItem Text="Brazil" Value="Brazil"></asp:ListItem>
    <asp:ListItem Text="Canada" Value="Canada"></asp:ListItem>
</asp:ListBox>
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass = "grid" AllowPaging = "true" OnPageIndexChanging = "OnPageIndexChanging">
    <Columns>
        <asp:BoundField HeaderText="Contact Name" DataField="ContactName" />
        <asp:BoundField HeaderText="Country" DataField="Country" />
    </Columns>
</asp:GridView>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
 
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
 
 
Populating the GridView
The GridView is populated inside the Page Load event handler. The GridView is populated using dynamic SQL Query built based on the ListBox multiple selections.
The ListBox’s items are iterated and if the item is selected then it is appended to the SQL Query.
Finally the SQL Query is completed by appending the WHERE clause and the GridView is populated.
The logic works as follows:-
When none of items in ListBox is selected the SQL Query is:
"SELECT ContactName, Country FROM Customers"
 
When items (say Argentina and Austria) are selected then the SQL Query is:
"SELECT ContactName, Country FROM Customers WHERE Country IN ('Argentina', 'Austria')"
Thus using the dynamic SQL Query, the GridView can be easily filtered based on ListBox multiple selections.
The GridView has been assigned OnPageIndexChanging event handler which simply assigns the new PageIndex to the GridView and rebinds it.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT ContactName, Country FROM Customers";
 
    string condition = string.Empty;
    foreach (ListItem item in lstCountries.Items)
    {
        condition += item.Selected ? string.Format("'{0}',", item.Value) : "";
    }
 
    if (!string.IsNullOrEmpty(condition))
    {
        condition = string.Format(" WHERE Country IN ({0})", condition.Substring(0, condition.Length - 1));
    }
 
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand(query + condition))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                cmd.Connection = con;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}
 
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    this.BindGrid();
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Private Sub BindGrid()
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT ContactName, Country FROM Customers"
 
    Dim condition As String = String.Empty
    For Each item As ListItem In lstCountries.Items
        condition += If(item.Selected, String.Format("'{0}',", item.Value), "")
    Next
 
    If Not String.IsNullOrEmpty(condition) Then
        condition = String.Format(" WHERE Country IN ({0})", condition.Substring(0, condition.Length - 1))
    End If
 
    Using con As New SqlConnection(conString)
        Using cmd As New SqlCommand(query & condition)
            Using sda As New SqlDataAdapter(cmd)
                cmd.Connection = con
                Using dt As New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub
 
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
    GridView1.PageIndex = e.NewPageIndex
    Me.BindGrid()
End Sub
 
 
Handling the SelectedIndexChanged event handler of ListBox
The following event handler is executed when the ListBox’s items are selected or unselected
Inside the event handler, the GridView is again populated so that the records can be filtered as per the latest selections.
C#
protected void Country_Selected(object sender, EventArgs e)
{
    this.BindGrid();
}
 
VB.Net
Protected Sub Country_Selected(sender As Object, e As EventArgs)
    Me.BindGrid()
End Sub
 
 
Screenshot
Filter GridView based on ListBox multiple selections in ASP.Net
 
 
Demo
 
 
Downloads
Download Code