Populate 2nd drop-down list box based on selected values in 1st drop-down list box

Hi Group,
I have two DDL boxes on my page.  DDL one has a list of values and a code.
e.g
code  Value
ABC   123
ABC   345
FGH   123

DDL 2 should only show values for the code selected in  DDL1 e.g  if user selects record 1 with code ABC
then DDL2 should show ALL records with the linked field value of ABC.

The tables are normalized.  For your info, the name of the field of the value I would like to check is called sublistcode.
Using vb.net

 TIA 

 

 

 

0
axapta
5/26/2008 12:44:23 PM
asp.net.web-forms 93655 articles. 6 followers. Follow

6 Replies
1632 Views

Similar Articles

[PageSpeed] 33

 Try this code:

 Note: Set appenddatabounditems to true for both dropdownlistboxes

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    SqlConnection con = new SqlConnection("server=server;uid=sa;pwd=sa;database=pubs");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SqlDataAdapter da = new SqlDataAdapter("select code,value from sublist", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DropDownList1.Items.Insert(0, new ListItem("Select a code", "-1"));
            DropDownList1.DataTextField = "code";
            DropDownList1.DataValueField = "value";
            DropDownList1.DataSource = ds;
            DropDownList1.DataBind();

           
        }
    }

    public void BindGrid(string query)
    {
        SqlDataAdapter da1 = new SqlDataAdapter(query, con);
        DataSet ds1 = new DataSet();
        da1.Fill(ds1);
        DropDownList2.DataTextField = "code";
        DropDownList2.DataValueField = "value";
        DropDownList2.DataSource = ds;
        DropDownList2.DataBind();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string qry="select * from table2 where code='"+DropDownList1.SelectedItem.Text+"'";
        BindGrid(qry);
    }
}
  

 

 

 


Mark as Answer if the post was useful to you

Rajesh Thangarasu
Microsoft Certified Professional
0
rajeshthangarasu
5/26/2008 12:53:48 PM

 http://authors.aspalliance.com/timmusschoot/aspdotnet/dropdownrewrite.aspx

 


If this solves your problem please mark as answer
0
Raggers
5/26/2008 12:59:03 PM

axapta:

Hi Group,
I have two DDL boxes on my page.  DDL one has a list of values and a code.
e.g
code  Value
ABC   123
ABC   345
FGH   123

DDL 2 should only show values for the code selected in  DDL1 e.g  if user selects record 1 with code ABC
then DDL2 should show ALL records with the linked field value of ABC.

The tables are normalized.  For your info, the name of the field of the value I would like to check is called sublistcode.
Using vb.net

 TIA


Here's a sample snippet for you 

Protected Sub PopulateDropDownList1()
   
    Dim queryString As String = "SELECT Code FROM Table1"
    Dim connection As New SqlClient.SqlConnection("Data Source=HCISSQL2;Initial Catalog=...;User ID=apps;Password=...")
   
    Dim command As New SqlClient.SqlCommand(queryString, connection)
   
    connection.Open()
   
    Dim dt As New DataTable()
    Dim ad As New SqlDataAdapter(command)
    ad.Fill(dt)
    If dt.Rows.Count > 0 Then
       
        DropDownList1.DataSource = dt
        DropDownList1.DataTextField = "Code"
        DropDownList1.DataValueField = "Code"        
        DropDownList1.DataBind()
    End If
   
    connection.Close()
   
End Sub 

Protected Sub PopulateDropDownList2(ByVal val As String)
   
    Dim queryString As String = "SELECT SubListCode FROM Table1 where Value = @value"
    Dim connection As New SqlClient.SqlConnection("Data Source=HCISSQL2;Initial Catalog=...;User ID=apps;Password=...")
   
    Dim command As New SqlClient.SqlCommand(queryString, connection)
    command.Parameters.AddWithValue("@value", val)
    connection.Open()
   
    Dim dt As New DataTable()
    Dim ad As New SqlDataAdapter(command)
    ad.Fill(dt)
    If dt.Rows.Count > 0 Then
       
        DropDownList2.DataSource = dt
        DropDownList2.DataTextField = "SubListCode"
        DropDownList2.DataValueField = "SubListCode"
        DropDownList2.DataBind()
    End If
    connection.Close()
   
End Sub 

Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    PopulateDropDownList2(DropDownList1.SelectedItem.Text)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
   
    If Not Page.IsPostBack Then 
        PopulateDropDownList1()
    End If
End Sub 


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
5/26/2008 1:44:50 PM

Hi Thanks for your replies but my selectedindexchanged module is not executing.

I have the following:

 Private Sub ddlQuota_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlQuota.SelectedIndexChanged
        Dim drSubList As SqlDataReader
        Dim strCommand As String

        If Not Page.IsPostBack Then
            strCommand = "sp_SubList_dropdown"

            cmdDBCommand.Connection = connDBConnect
            cmdDBCommand.CommandText = strCommand
            cmdDBCommand.CommandType = CommandType.StoredProcedure
            cmdDBCommand.Parameters.Add("@pWhereClause", ddlQuota.SelectedItem.Text)
            Try
                drSubList = cmdDBCommand.ExecuteReader
                ddlSubList.Items.Add(New ListItem("", ""))
                While drSubList.Read
                    ddlSubList.Items.Add(New ListItem(drSubList("sublistdesc"), drSubList("sublistcode")))
                End While
                drSubList.Close()


            Catch ex As Exception

            End Try
            ' cmdDBCommand.Connection.Close()
        End If
    End Sub

0
axapta
5/31/2008 7:36:23 PM

The ddlQuota_SelectedIndexChanged only fires when I hit the clearall button on my page which just resets fields to null and the two ddl's as follows:

me.ddlquota.selectedindex=0

me.ddlsublist.selectedindex = 0

Is it to do with postback?  I can't figure this one out.

Thanks

0
axapta
5/31/2008 8:43:37 PM

axapta :

Hi Thanks for your replies but my selectedindexchanged module is not executing.

You need to set the attribute AutoPostBack = true in your DDL for you to fire up the SelectedIndexChanged event of DDL..


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
6/2/2008 2:00:52 PM
Reply:

Similar Artilces:

Update 2 drop-down list based on values of the 1 drop-down list box
 Hi,I am using ASP.NET,C# and SQL ServerI have 2 Drop down list boxes.In first List box I have: countries ...I need to Update 2 text box with corresponding states...I am getting these values from database both country and states... How to implement this ..can anyone help me on this...Please provide some code examples ...It will be helpful... Did you checked Ajax CascadingDropDown ?  My Blog"Don't be afraid to be wrong; otherwise you'll never be right." Create a Sub to handle the SelectedIndexChanged of your Country drop down.  Anytime the country i...

Load Text box of one web form with selected list item of list box of another web form
one help please Problem is i have two web forms  1.  ForiegnkeyTest.aspx  2. foroginkeytable.aspx   step 1 1 ForiegnkeyTest.aspx one web form <head runat="server"><script language="javascript" type="text/javascript">   function popWin()   {         var confirmWin = null;      confirmWin = window.open('foroginkeytable.aspx','anycontent',   'width=455,height=435,status');   }  </script> &...

How to get the list of second drop-down-list based on value selected in the first drop-down-list
I have two drop-down-lists, the second one depends on the value chosen in the first drop-down-list.  In the first drop-down-list, I have AutoPostBack = "true" and OnSelectedIndexChanged = "SelectedIndexChanged" In the selectedIndexChanged method, I do the following: 1    protected void SelectedIndexChanged(object sender, EventArgs e)2        {3            if (IsPostBack)4            {5      &nbs...

How to populate one drop down list based on the item selected in another drop down list?
Hello Mate,                      I have two drop down lists. I have to populate one drop down list from Database  based on the selection of an item in another drop down list. And i dont want the page to be posted back while performing this operation.                      If you have an idea about my issue, Please let me know!.Much Obliged & Thanks a Lot,Myself Hi, you can craft ...

Drop Down List Populated Depending Upon the value Selected in another Drop Down List
  I have five drop down lists.Each One populated based on the value selected in the previious one. I have used SqlDataSource for binding data to each drop down.And I need some initial value so I put "AppendDataBoundItems" as true.Functionality is ok. The problem is, I have selected one from first dropdown.then second drop down is populated.but now i want to select a different value from first dropdown.If i do so,To my second drop down list the values r being appended.not refreshed.I think this is because AppendDataBoundItems=true Plz suggest me something. Thanks in Advan...

Populate a second drop down list upon selection value of the first drop down list in a gridview
How to Populate a second drop down list upon selection value of the first drop down list in a gridview? DropDownList1 ******************* <asp:TemplateField HeaderText="SystemName" SortExpression="SystemName">                <EditItemTemplate>                    <asp:DropDownList ID="sysidddl" runat="server" DataSourceID="sysods1"    &nbs...

how to select the value of the drop down list box based on a string
Hello THere!,i have a drop down list box in my web formIn Add mode Actually i am filling it from database.all i need is In modify mode the selected value of the drop down should be shown as the same string which i would pass in the address bar by giving like http://some page.aspx?code=erp.that is after in the modify mode the selected value of the drop down should be changed as ERP when i give code=erpIf you know any solution please let me know!Much Obliged & Thanks a Lot,Myself u have to loop thru items to compare the value and select appropriate item.Mark as answer if you are agree...

how to make one list box(this list box should have selected products) gets filled from another list box (for example this list box has the whole products) by using navigation control
Hello Mate!, I have two list boxes. one should get populated with whole products. and i have another list box in which i have to move some of the products which i like .   The design should be the one below: List Box1   List Box 2 all products   Selected products BMW    >> BMW BENZ     > LEXUS AUDI     <   LEXUS    <<     Could you please suggest me whether i have to use buttons(by which i move items from one list box to another)  ...

Adding Values in List Box from Drop Down List
 Hi I need help in adding values into a list box from a drop down list (Which is already populated form the database.) Regards Mirza Try to use AppandDataBoundItems and you can add the listitems into the dropdown like this way     <asp:DropDownList ID="ddlPartnerType" runat="server" Width="150px" AppendDataBoundItems="True">             <asp:ListItem Value="-1">Select one...</asp:ListItem>    </asp:DropDownList> my perso...

AppendDataBoundItems="true" doesn't work for 2nd drop down box that is "filtered" based on selection of first drop down box.
I have two drop down boxes.  Department, and Employees.  In my vb.net form, when a user selects Department, the Employees dropdown binds, but instead of listing the first name, I want to list "Please make a selection"... I've tried the appenddatabounditems (see below), but it doesn't seem to work.  What am I missing?? <asp:SqlDataSource ID="getDept" runat="server" ConnectionString="<%$ ConnectionStrings:xxxConnectionString %>"SelectCommand="sp_GetDepartments" SelectCommandType="StoredProcedure">&l...

FormView: Filter a drop-down list based on a selection in another drop-down list
Hi Everyone, I have a FormView and in it is a drop-down list for "Clients". Below it is another drop-down list: "Contact". The database is set-up so that each clinet has one or more contacts. So, when I change the selected client, I want the list of contact to update. Here's the code: '> " SelectCommand="SELECT [Client_ID], [Client_Name_Short] FROM [tbl_Clients] WHERE ([Is_Active] = @Is_Active) ORDER BY [Client_Name_Short]"> ...

Drop Down List in a Data List =- How can I select a specific item in Drop Down List
I have put a drop down list into a data list. It will have a list of cities in it related to the market I am writing this for. I need to have this select the city where a current customer is doing business so that if they move they can use this drop down to select the city they moved to in the market How do I set a default row in the dropdown? I now goes to row 0, probably the wrong one If you know what the default value is supposed to be, the easiest way to preset the dropdownlist control is to write code in the ItemDataBound event of the DataList using the FindControl method to get ...

Populate Text Boxes using the value from a Drop Down List
I have a drop down box that contains values retreived from an Access database. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load DDLSelectCust.DataSource = GetCompanyInfo DDLSelectCust.DataMember = "Customers" DDLSelectCust.DataTextField = "CompanyName" DDLSelectCust.DataValueField = "CustomerID" DDLSelectCust.DataBind() End Sub I have several other text boxes on the same page. How can I use the ...

Populate gridview based on drop down list selected value
I have a dropdown list populated with table names. After a tablename is selected from the dropdownlist, my grid view should be populated. I am trying to assign String Var = Convert.ToString(dropdownlist1.selectedvalue ); In select statement,:"Select * From " +Var but this is not working.  How should i do this. ThanksGans      Hi, gvenkat:Here is the sample of appending the parameters to the sqlcommand statement. I have no idea about  your senario but hope this helps you to the right direction . If you still have the problem, maybe you can d...

Web resources about - Populate 2nd drop-down list box based on selected values in 1st drop-down list box - asp.net.web-forms

ASUS’ ZenWatch drops down to $150
... recent announcement of the Asus ZenWatch 2 at Computex, Amazon and Best Buy have decided to lower the price of the first generation model down ...

[Deal Alert] New Unlocked 32GB Samsung Galaxy S6 Edge Drops Down To Just $550 On eBay
Some electronics are quick to dip in price. Sure, a game console may cling to its original cost for years after launch, but it's not uncommon ...


Deal: Motorola's Moto 360 smartwatch drops down to just $149.99
The Moto 360, which is widely considered to be one of the better-looking wrist-worn gadgets on the market, has...

United Airlines 4Q profit drops 80 percent on write-downs
CHICAGO (AP) — United Airlines' fourth-quarter profit fell 80 percent due to severance costs and contracts that lost value as oil prices tumbled. ...






Resources last updated: 12/24/2015 1:13:28 PM