Hello all,

I have ddlA that loads another ddlB on a postback. I AM Able to get ddlA to load in the page load event;however, i can not get the ddlB to load from the selected value from ddlA.
Can someone please help me with this.

* I am very much open to all solutions for this issue. IF YOU have a better way or an easier way of doing this, by all means, please share it with me!

Erik.

'
    'GO NOW!
    '
    Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then
            Customers()
        End If
    End Sub
    '
    Private Sub Customers()
        ddlCustomers.DataSource = GetData()
        ddlCustomers.DataTextField = "CompanyName"
        ddlCustomers.DataValueField = "CompanyName"
        ddlCustomers.DataBind()
    End Sub
    '
    Private Sub LoadList()
        ddlCompanyName.Items.Clear()
ddlCompanyName.DataSource = GetData(ddlCustomers.SelectedValue).CompanyName 'ado.net query
        ddlCompanyName.DataBind()
    End Sub
    '''''
    '...Northwind
    ''''
    Function GetData()
        '
        Dim cnn As New SqlConnection("data source= desktop; initial catalog= northwind; trusted_Connection=yes")
        '
        Dim cmd As New SqlCommand("SELECT * FROM Customers", cnn)
        cmd.CommandType = CommandType.Text
        '
        cnn.Open()
        Dim result As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        Return result
        cnn.Close()
        result.Close()
    End Function
    '
End Class 'STOOOOOOOOP!...

===============================================Drop Downs.................

<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
			<TABLE id="Table1" style="Z-INDEX: 101; LEFT: 136px; WIDTH: 504px; POSITION: absolute; TOP: 88px; HEIGHT: 167px"
				cellSpacing="1" cellPadding="1" width="504" border="1">
				<TR>
					<TD style="HEIGHT: 85px"></TD>
					<TD style="WIDTH: 183px; HEIGHT: 85px"></TD>
					<TD style="HEIGHT: 85px"><asp:dropdownlist id="ddlCompanyName" runat="server" AutoPostBack="True"></asp:dropdownlist></TD>
				</TR>
				<TR>
					<TD style="HEIGHT: 24px"></TD>
					<TD style="WIDTH: 183px; HEIGHT: 24px">Company Name</TD>
					</TD></TR>
				<TR>
					<TD></TD>
					<TD style="WIDTH: 183px">Customers</TD>
					<TD><asp:dropdownlist id="ddlCustomers" runat="server" AutoPostBack="True"></asp:dropdownlist></TD>
				</TR>
			</TABLE>
		</form>
	</body>

Recommended Answers

All 12 Replies

What error are you getting?
Can you post the error code..and where is your ddA selected value
changed event?

Hello Letscode,

I hope that you can help.. I have a good idea to what is going on here i just do not know how to solve the problem.. I think that the datalist dissapears on the post back because there is no parameter to supply to it. There only time that it receives parameter is when the page first loads. And i need help solving this issue.. Any help is great!!

Thank you,,

Erik...

Code=====================================..

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here

        'If Page.IsPostBack Then

        ' Obtain IDProduct & IDProductgroup from QueryString
        Dim IDCompany As Integer = CInt(Request.Params("IDCompany"))
        Dim IDProductgroup As Integer = CInt(Request.Params("IDProductgroup"))

        Dim myMetroProdcuts As New ConstructionSuperCenterCom.Menus

        dlMetroMenu.DataSource = myMetroProdcuts.GetTopMETRoMenu(IDCompany, IDProductgroup)
        dlMetroMenu.DataBind()
 

    End Sub
End Class

=================================---

Namespace ConstructionSuperCenterCom


    Public Class Menus

        Function GetTopMETRoMenu(ByVal IDCompany As Integer, ByVal IDProductgroup As Integer) As SqlDataReader

            'Create an Instant of the connection AND a Command
            Dim cnn As New SqlConnection(ConfigurationSettings.AppSettings("cnn"))
            Dim cmdLoadMenu As New SqlCommand("Load_Menu_For_Companys", cnn)

            ' Mark the Command as a SPROC
            cmdLoadMenu.CommandType = CommandType.StoredProcedure

            ' Add Parameters to SPROC
            Dim ParameterIDCompany As New SqlParameter("@IDCompany", SqlDbType.Int, 4)
            ParameterIDCompany.Value = IDCompany
            cmdLoadMenu.Parameters.Add(ParameterIDCompany)
            '
            Dim ParamIDProductgroup As New SqlParameter("@IDProductgroup", SqlDbType.Int, 4)
            ParamIDProductgroup.Value = IDProductgroup
            cmdLoadMenu.Parameters.Add(ParamIDProductgroup)

            ' Execute the command
            cnn.Open()
            Dim result As SqlDataReader = cmdLoadMenu.ExecuteReader(CommandBehavior.CloseConnection)

            ' Return the datareader result
            Return result

        End Function

----------------------------Datalist............................

<asp:datalist id="dlMetroMenu" Width="714px" runat="server" RepeatColumns="4" RepeatDirection="Horizontal"
				Height="40px" CellPadding="2" BorderColor="#66CCCC" CellSpacing="5" BorderStyle="Dotted" BorderWidth="1px">
				<SelectedItemTemplate>
					<asp:HyperLink id=Hyperlink2 runat="server" NavigateUrl='<%# "\ConstructionSuperCenterCom/WindowTreatment_ByCompany.aspx?IDCompany=" &amp; DataBinder.Eval(Container.DataItem, "CompanyID") &amp; "&amp;IDCompanyProductCategory=" &amp; DataBinder.Eval(Container.DataItem, "CompanyProductCategoryID") &amp; "&amp;CompanyProductCategoryName=" &amp; DataBinder.Eval(Container.DataItem, "CompanyProductCategoryName")%>' Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>' cssclass="MenuSelected">
					</asp:HyperLink>
				</SelectedItemTemplate>
				<AlternatingItemStyle BackColor="#FFFFCC"></AlternatingItemStyle>
				<ItemTemplate>
					<asp:HyperLink id=Hyperlink1 runat="server" NavigateUrl='<%# "\ConstructionSuperCenterCom/WindowTreatment_ByCompany.aspx?IDCompany=" &amp; DataBinder.Eval(Container.DataItem, "CompanyID") &amp; "&amp;IDCompanyProductCategory=" &amp; DataBinder.Eval(Container.DataItem, "CompanyProductCategoryID") &amp; "&amp;CompanyProductCategoryName=" &amp; DataBinder.Eval(Container.DataItem, "CompanyProductCategoryName") %>' Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>' cssclass="MenuSelected">
					</asp:HyperLink>
				</ItemTemplate>
			</asp:datalist>

' Thank you...

Erik,
I suggest you do ONE step at a time.

1.Populate the values for ddA.

a.Set the Autopostback property to True for ddA

Check this.ddA

b.This is ddB,
ddB
Set the Autopostback property to True for ddB

2.From the selected value in ddA ,Populate ddB.

Select a value from ddA,
http://www.geocities.com/blood_boys7/selectcounty.JPG

ddB will be populated,
http://www.geocities.com/blood_boys7/selecttrack.JPG

I wrote a quick program that will help you.

Read those codes.I REPEAT TRACE THE PROGRAM AND UNDERSTAND HOW ITS WORKING.

Its always confusing to go to step 3 without completing step 2.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim conncounty As SqlConnection
        Dim cmdcounty As SqlCommand
        Dim Scounty As String
        Dim Strcounty As String = "Select a county"
        conncounty = New SqlConnection("server = localhost;database=17jan2005;user=sa;pwd=;")
        Scounty = "SELECT DISTINCT COUNTY FROM Databas"
        If Page.IsPostBack = False Then
            Dim dreader As SqlDataReader
            conncounty.Open()
            cmdcounty = New SqlCommand(Scounty, conncounty)
            dreader = cmdcounty.ExecuteReader()
            Dim firstrow As Boolean = True
            ddA.Items.Add(Strcounty)
            While dreader.Read()
                ddA.Items.Add(New ListItem(dreader(0).ToString()))
            End While
            dreader.Close()
            conncounty.Close()
        End If
    End Sub
    Private Sub ddA_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddA.SelectedIndexChanged
        Dim conntrack As SqlConnection
        Dim cmdtrack As SqlCommand
        Dim Strack As String
        Dim Strtrack As String = "Select  a Tract "
        Dim url As String
        Dim county1 As String

        conntrack = New SqlConnection("server=localhost;database=17jan2005;;user=sa;pwd=;")
        Strack = "SELECT TRACTID FROM Databas WHERE COUNTY = @county AND TRACTID <> '0'"
        county1 = ddA.SelectedItem.Text
        conntrack.Open()
        ddB.Items.Clear()
        Dim dreader1 As SqlDataReader
        cmdtrack = New SqlCommand(Strack, conntrack)
        cmdtrack.Parameters.Add(New SqlParameter("@county", SqlDbType.VarChar)).Value = county1
        dreader1 = cmdtrack.ExecuteReader()
        Dim firstrowfortrack As Boolean = True
        ddB.Items.Add(Strtrack)
        While dreader1.Read()
            ddB.Items.Add(New ListItem(dreader1(0).ToString()))
            If (firstrowfortrack) Then
                firstrowfortrack = False
            End If
        End While
        dreader1.Close()
        conntrack.Close()
    End Sub

3.After getting the values on the second drop down box,then double click the ddB and you'll go to code behind,

Private Sub ddB_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddB.SelectedIndexChanged

'Populate the Datalist

End Sub

Hope it helps.

I'll try to correct your code when I have sometime.

Thank you for taking the time to send me this information. I look forward to looking over the code! :p

Thank you,
Erik...

Excellent clean code letscode. Good advice as well. The use of breakpoints and following through an interation of your code can provide worlds of information as to what is going on...which is often different than what you thought or intended to happen.

Hope it works out for you Erik.

Please Use Code Blocks Erik when posting

Happy Coding :cool:

Thanks Paladine.

Had a nice day today,not much work to do. :D

So I thought I will work on Eric problem.In fact I saw this post a couple of times in many forums.All beginners go through this process.

This is what I came up with.

What does this code do?
This application has two dropdownlist and a datalist.

What this application does
1.It populates the first dropdownlist from the database.
2.It populates second dropdownlist by using the value selected from the first dropdownlist.
3.If populates the Datalist by values from both the dropdownlist.

http://www.geocities.com/blood_boys7/mainpage.JPG


STEP 1:Select company name
http://www.geocities.com/blood_boys7/selectcompany.JPG
This is the first Filter Condition.

STEP 2:Select Customer Name
http://www.geocities.com/blood_boys7/selectname.JPG
Second Filter condition.

STEP 3:Select the properties of the values from your STEP 2 and STEP 1:
Eg.
Like address and city of the customer name
http://www.geocities.com/blood_boys7/datalist.JPG

I was not sure of your Datalist Eric,so I used a different example for the last step.

This is the design screen.
http://www.geocities.com/blood_boys7/mainpage.JPG


This is the HTML CODE.

<HTML>
 <HEAD>
  <title>WebForm3</title>
        http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
 </HEAD>
   <form id="Form1" method="post" runat="server">
   <asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 136px" runat="server"
    BorderColor="Gray" BorderWidth="2px">
    <ItemTemplate>
     <TABLE style="FONT-WEIGHT: normal; FONT-SIZE: small; WIDTH: 376px; HEIGHT: 230px" border="0">
      <TR>
       <TD style="FONT-WEIGHT: bold; COLOR: white; FONT-STYLE: normal" bgColor="#4a3c8c">FIELDS
       </TD>
       <TD style="FONT-WEIGHT: bold; COLOR: white; FONT-STYLE: normal" align="right" bgColor="#4a3c8c">ATTRIBUTE</TD>
      </TR>
      <TR bgColor="#ffffff">
       <TD>CustomerID</TD>
       <TD align="right"><%# DataBinder._Eval(Container.DataItem, "CustomerID") %></TD>
      </TR>
      <TR>
       <TD bgColor="#ccccff">CompanyName</TD>
       <TD align="right" bgColor="#ccccff"><%# DataBinder._Eval(Container.DataItem, "CompanyName")%></TD>
      </TR>
      <TR bgColor="#ffffff">
       <TD>ContactName</TD>
       <TD align="right"><%# DataBinder._Eval(Container.DataItem, "ContactName") %></TD>
      </TR>
      <TR>
       <TD bgColor="#ccccff">ContactTitle</TD>
       <TD align="right" bgColor="#ccccff"><%# DataBinder._Eval(Container.DataItem, "ContactTitle") %></TD>
      </TR>
      <TR bgColor="#ffffff">
       <TD>Address</TD>
       <TD align="right"><%# DataBinder._Eval(Container.DataItem, "Address") %></TD>
      </TR>
      <TR>
       <TD bgColor="#ccccff">City</TD>
       <TD align="right" bgColor="#ccccff"><%# DataBinder._Eval(Container.DataItem, "City") %></TD>
      </TR>
      <TR bgColor="#ffffff">
       <TD>PostalCode</TD>
       <TD align="right"><%# DataBinder._Eval(Container.DataItem, "PostalCode") %></TD>
      </TR>
      <TR>
       <TD bgColor="#ccccff">Country</TD>
       <TD align="right" bgColor="#ccccff"><%# DataBinder._Eval(Container.DataItem, "Country") %></TD>
      </TR>
     </TABLE>
    </ItemTemplate>
   </asp:DataList>

   <TABLE id="Table1" cellSpacing="1" cellPadding="1" width="376" border="2" style="Z-INDEX: 102; LEFT: 8px; WIDTH: 376px; POSITION: absolute; TOP: 16px; HEIGHT: 118px"
    borderColor="#663366">
    <TR>
     <TD style="WIDTH: 183px; HEIGHT: 24px">Company Name</TD>
     <TD style="HEIGHT: 85px"><asp:dropdownlist id="ddlCompanyName" runat="server" AutoPostBack="True" Width="176px"></asp:dropdownlist></TD>
    </TR>
    <TR>
     <TD style="WIDTH: 183px">Customers</TD>
     <TD><asp:dropdownlist id="ddlCustomers" runat="server" AutoPostBack="True" Width="176px"></asp:dropdownlist></TD>
    </TR>
   </TABLE>
  </form>
 </HTML>

This is the code behind.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim conncounty As SqlConnection
        Dim cmdcounty As SqlCommand
        Dim Scounty As String
        Dim Strcounty As String = "Select a Company"
        conncounty = New SqlConnection("server = localhost;database=Northwind;user=sa;pwd=;")
        Scounty = "SELECT DISTINCT CompanyName FROM Customers"
        If Page.IsPostBack = False Then
            Dim dreader As SqlDataReader
            conncounty.Open()
            cmdcounty = New SqlCommand(Scounty, conncounty)
            dreader = cmdcounty.ExecuteReader()
            Dim firstrow As Boolean = True
            ddlCompanyName.Items.Add(Strcounty)
            While dreader.Read()
                ddlCompanyName.Items.Add(New ListItem(dreader(0).ToString()))
            End While
            dreader.Close()
            conncounty.Close()
        End If
    End Sub
    
Private Sub ddlCustomers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCustomers.SelectedIndexChanged
        Dim connfid As SqlConnection
        Dim mycommand As SqlDataAdapter
        Dim Sviet As String
        Dim Vcounty As String
        Dim Vtrack As String
        connfid = New SqlConnection("server = localhost;database=Northwind;user=sa;pwd=;")
        If (Page.IsPostBack = True) Then
            connfid.Open()
            Vcounty = ddlCompanyName.SelectedItem.Text
            Vtrack = ddlCustomers.SelectedItem.Text
            Sviet = "SELECT  * FROM Customers WHERE ContactName LIKE @track  AND CompanyName LIKE @county"
            mycommand = New SqlDataAdapter(Sviet, connfid)
            mycommand.SelectCommand.Parameters.Add(New SqlParameter("@county", SqlDbType.VarChar)).Value = Vcounty
            mycommand.SelectCommand.Parameters.Add(New SqlParameter("@track", SqlDbType.VarChar)).Value = Vtrack
            Dim ds As DataSet = New DataSet
            mycommand.Fill(ds)
            DataList1.DataSource = ds
            DataList1.DataBind()
            End If
        connfid.Close()
    End Sub
    
Private Sub ddlCompanyName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCompanyName.SelectedIndexChanged
        Dim conntrack As SqlConnection
        Dim cmdtrack As SqlCommand
        Dim Strack As String
        Dim Strtrack As String = "Select  a Customer"
        Dim url As String
        Dim county1 As String
        conntrack = New SqlConnection("server=localhost;database=Northwind;user=sa;pwd=;")
        Strack = "SELECT ContactName FROM Customers WHERE CompanyName LIKE @county "
        county1 = ddlCompanyName.SelectedItem.Text
        conntrack.Open()
        ddlCustomers.Items.Clear()
        Dim dreader1 As SqlDataReader
        cmdtrack = New SqlCommand(Strack, conntrack)
        cmdtrack.Parameters.Add(New SqlParameter("@county", SqlDbType.VarChar)).Value = county1
        dreader1 = cmdtrack.ExecuteReader()
        Dim firstrowfortrack As Boolean = True
        ddlCustomers.Items.Add(Strtrack)
        While dreader1.Read()
            ddlCustomers.Items.Add(New ListItem(dreader1(0).ToString()))
            If (firstrowfortrack) Then
                firstrowfortrack = False
            End If
        End While
        dreader1.Close()
        conntrack.Close()
    End Sub

Things to do
1.First copy,paste this code and play around with it.Keep break point and test the code.I used a Northwind database so that everyone can test it,

Just copy ,paste the codebehind as a new project and test it.

FOR YOUR APPLICATION
2.Remove the stored procedure,Use Queries directly like this example for now, then you can use a stored procedure once you get it to work.

3.Just insert your three queries inside strings Scounty, Sviet,Strack.One for First dropdownlist,Second dropdownlist and last for datalist.

4.Change the database to suit your application.

5.If you take a look at the datalist in this example,you can easily tune up yours.

NOTE:
Take a look at the use of tables in Datalist.Notice the use of tags <tr> and <td> to arrange the datalist in any way you need.

<tr> Creates a row and
<td> Creates a column.

Remember first check how this example works and then proceed with your application.


Hope it helps.

Hello i wanted to come back and let the person know that posted this example that they did a awsome job!!!! Very nice..

Thank you so much for your effort!

Erk...

No problem

I have a question for you.. :)

I have a question about the .ToString... Since it is in your code and i am tring to make since out of it.. every thing that i read about the tostring adn the get type is leaving gaps in my learning experience..

However, i think i am picking up on it by looking at your code...

In your code when you write ----> While dreader.Read()
ddlCompanyName.Items.Add(New ListItem(dreader(0).ToString()))
End While <-------------

are you doing the .ToString so that the value of the string can be used in the ---> Vcounty = ddlCompanyName.SelectedItem.Text <------- in the ddlCustomers_SelectedIndexChanged event ??????

is this the biggest way that the .TOString is used?? Any points that you would like to make would be great... about the .ToString and the .Gettype......

:cheesy:

Erik,,,,

Your First question,

In your code when you write ----> While dreader.Read()
ddlCompanyName.Items.Add(New ListItem(dreader(0).ToString()))
End While <-------------

I'll explain you what this code does.

While dreader.Read()
                ddlCompanyName.Items.Add(New ListItem(dreader(0).ToString()))
            End While

In the database,if there is only one value to be populated you can use something like this

ddlCompanyName.Items.Add(New ListItem(dreader(0).ToString()))

But in our database there are more than one value to be populated inside the DropDownlist,

For example say,

CompanyA
CompanyB
CompanyC
CompanyD

Say you wanna populate these four values into the database,
your first step will be to use a DataReader to store these four values into the database.

Once you execute this code,

dreader = cmdcounty.ExecuteReader()

CompanyA
CompanyB
CompanyC
CompanyD

All the four Company values will be store into the DataReader.

Then if you use this code,

ddlCompanyName.Items.Add(New ListItem(dreader(0).ToString()))

Only the value CompanyA will be populated into the DropDownlist.

But you need the four values to be populated into the DropDownlist.

So you write somekind of a loop,

While dreader.Read()
                ddlCompanyName.Items.Add(New ListItem(dreader(0).ToString()))
            End While

What this code does is that it reads the DataReader,
1.checks whether Datareader has any values.

2.If there are any values then the second line in the code will be executed,

ddlCompanyName.Items.Add(New ListItem(dreader(0).ToString()))

This code creates a NEW ITEMLIST and then populates the value from the dataReader into the DropDownlist,

3.Since its a while loop it goes back to Step 1 and grabs the second item in the Datareader and goes to step 2 . This continues until Datareader fails to read any more items in its list.

Now the Dropdownlist has All the four Company values,

CompanyA
CompanyB
CompanyC
CompanyD


I hope that answers your first question.

Now regarding you second question,

are you doing the .ToString so that the value of the string can be used in the ---> Vcounty = ddlCompanyName.SelectedItem.Text <------- in the ddlCustomers_SelectedIndexChanged event ??????

Your answer is YES.

Since I declared Vcounty as a String,

Dim Vcounty As String

I needed to convert values in the dreader to String.

I hope that helps.

Thank you for helping me with this! :cheesy:

I seem late to respond that it because i try to let as much soak in as i can.. This to string is really bothering me... I have paper taped up on my walls with different defenitions and it still is not completely soaking in.. My main concern here is that i know when hte .Tostring is used,, it enables a representation of the current object to be accessed,, HERE is the question... Where is it held until it is used??? .Tostring,, (to where???) at run time does the string go directly to the object that will utilize its value?,.,

I know these are small patatos; however, i am in need to get a better understanding about this..

I am missing something some where..

Erik...

Thank you for helping me with this! :cheesy:

I seem late to respond that it because i try to let as much soak in as i can.. This to string is really bothering me... I have paper taped up on my walls with different defenitions and it still is not completely soaking in.. My main concern here is that i know when hte .Tostring is used,, it enables a representation of the current object to be accessed,, HERE is the question... Where is it held until it is used??? .Tostring,, (to where???) at run time does the string go directly to the object that will utilize its value?,.,

I know these are small patatos; however, i am in need to get a better understanding about this..

I am missing something some where..

Erik...

Hmm.I'm not sure what you are asking.
The .Tostring is a property which converts the values in the DataReader to a string.

Thats It.Its just a property.Even if you remove the Tostring property your code will work.

Only thing to be noted is you'll have to keep track of dataType of the values which you are accessing in the DataReader if you remove the ToString Property.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.