Suppose you have two list box, ListBox1 and ListBox2 and you want to populate values of ListBox2 according to the selection in ListBox1 then it’s very simple you can just use to find the value of your selected item of you ListBox1 and execute your query accordingly.
But, what if ListBox1 is multiselect list box, i.e. SelectionMode="Multiple" of ListBox1. Then in that case you will have to display all the records related to all the selected items in the first list box.
Now, here I am going to show how we can accomplish this.
I have two list boxes, ListBox1 and ListBox2 and they both are bound with Data source.
Create statement for the tables used in this example.
create table tblSubCat (SubCatID int, SubCat varchar(50), CategoryID int)
create table tblCategory (CategoryID int, Category varchar(50))
Here is the aspx code for the file.
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" DataSourceID="SqlDataSource1" DataTextField="Category" DataValueField="CategoryID"></asp:ListBox>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>" SelectCommand="SELECT * FROM [tblCategory]"></asp:SqlDataSource>
<asp:ListBox ID="ListBox2" runat="server" DataSourceID="SqlDataSource2" DataTextField="SubCat" DataValueField="SubCatID"></asp:ListBox>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Text="Populate" OnClick="Button1_Click" />
According to the code above ListBox1 will be populated on page.
Now what we want to do is to populate the second list box according to the selections in ListBox1 if the selection is multiple, so in order to accomplish our goal we have to write some logic to find all the selected items in ListBox1.
Here is the code to accomplish the above goal.
protected void Button1_Click(object sender, EventArgs e)
string query = "";
for (int i = 0; i < ListBox1.Items.Count; i++)
if (ListBox1.Items[i].Selected == true)
if (query.Length > 0)
query = query + " or ";
query = query + " CategoryID=" + ListBox1.Items[i].Value;
if (query.Length > 0)
SqlDataSource2.SelectCommand = "Select * from tblSubCat where " + query;