Solved

Cascading DropDownLists in a FormView

Posted on 2010-11-08
2
879 Views
Last Modified: 2012-05-10
I have developed a page that incorporates both a GridView and a FormView template. When the "Select" button for a row in the GridView is clicked, details for that GridView item are displayed in the FormView below the GridView. The FormView helped me implement this page design.
However, I have two dropdownlists in the FormView template where the selection of an item in the first dropdownlist (Pet Species) determines what items are displayed in the second dropdownlist (Pet Breed.)
I have viewed a previous answer at expert-exchange for cascading dropdownlists in a FormView but it was not the same situation.
The following problems currently exist with my code due to use of the FormView template:
1) The list displayed in the Breed dropdownlist for the selected entry in the Species dropdownlist is not limited to breeds specific to the species selection. All breed table entries are displayed.
2) When a different value in the Species dropdownlist is selected the follwoing error occurs:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 83:     Sub loadBreed_SelectedIndexChanged( s As Object, e As EventArgs )
Line 84:           dim SpeciesOther as String
Line 85:           dim drpSpecies_text = drpPetSpecies.SelectedItem.Text
Line 86:           
Line 87:           breed_species_key = drpPetSpecies.SelectedItem.Value
 
I have found an example at a website that shows that I needed to add a Databound, an ItemUpdating, and a SelectedIndexChanged subroutine for the drpSpecies control. I was unable to get that code to work so I've submitted my previous code that did not have the Databound and ItemUpdating subroutines.
Sub Page_Load()		

    	If Not IsPostBack Then

       		lblOwnerKey.Text = Session( "owner_key" ) 		       		       		

       	Else

       	       	

       	End If		  

    End Sub

    Sub grdCitizen_RowCommand(ByVal sender as Object, ByVal e as GridViewCommandEventArgs)

    	dim index as Integer = Int32.Parse(CType(e.CommandArgument, String))

    	dim citizenkey as Integer = CType(grdCitizen.DataKeys(index).Values("citizen_key"), Integer)

    	Session( "citizen_key" ) = citizenkey

    	lblCitizenKey.Text = CType(citizenkey, String)

    	srcCitizenDetails.SelectParameters("citizen_key").DefaultValue = citizenkey

    End Sub

    Protected Sub frmCitizenDetail_ItemUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewUpdatedEventArgs) Handles frmCitizenDetail.ItemUpdated

        If e.AffectedRows > 0 AndAlso e.Exception Is Nothing Then

            grdCitizen.DataBind()

        End If

    End Sub

    Sub loadBreed_SelectedIndexChanged( s As Object, e As EventArgs )

    	dim SpeciesOther as String

    	dim drpSpecies_text = drpPetSpecies.SelectedItem.Text

    	

    	breed_species_key = drpPetSpecies.SelectedItem.Value

    	Load_Breed_DropDown()

    	

    	If txtSpeciesOther.Text Is Nothing Then

   			SpeciesOther = ""

   		Else

    		SpeciesOther = txtSpeciesOther.Text

    	End If

    	

    	If drpSpecies_text = "Other" And SpeciesOther = "" Then

    		Session( "valid_flag" ) = "N"

    	Else If drpSpecies_text <> "Other" And SpeciesOther > ""

    		txtSpeciesOther.Text = ""

    		Session( "valid_flag" ) = "Y"

    	Else

       		Session( "valid_flag" ) = "Y"

    	End If    	    

    End Sub

	Function Load_Breed_DropDown()



		'** Load Breed Drop Down List from Breed table Based on Species Selected in Species DropDown ListS

	

		dim strBreedSQL

		dim connectionString as String = WebConfigurationManager.ConnectionStrings("YPW").ConnectionString

		Dim conn As New SqlConnection(connectionString)

		

		strBreedSQL =	"SELECT * FROM tblBreed " & _

						" WHERE breed_species_key=" & breed_species_key & _

						" Order By breed_code, breed_name"

					

		'Try

			conn.Open()

			'** Execute the SQL String 

			dim BreedCmd As New SqlCommand(strBreedSQL, conn)

			Dim BreedReader As SqlDataReader = BreedCmd.ExecuteReader()

			drpPetBreed.DataSource = BreedReader

			drpPetBreed.DataTextField = "breed_name"

			drpPetBreed.DataValueField = "breed_key"

			drpPetBreed.DataBind()

			conn.Close()

			BreedReader.Close()

		'End Try



    End Function

<asp:GridView

															        id="grdCitizen"

															        DataSourceID="srcCitizen"

															        Width="500px"

															        DataKeyNames="citizen_owner_key, citizen_key"

															        AutoGenerateSelectButton="true"

															        AutoGenerateDeleteButton="false"

															        AutoGenerateColumns="false"

															        HeaderStyle-CssClass="HeaderStyle"	

															        EmptyDataText="No Citizens Registered"

															        SelectedRowStyle-BackColor="palegoldenrod"	

															        OnRowCommand="grdCitizen_RowCommand"

															        OnRowDataBound="grdCitizen_RowDataBound"												       

	 																ShowFooter="false"

	 																GridLines="None"

															        Runat="server" >

															 	<Columns>

															 		<asp:CommandField

															            ButtonType="Button"

															            ShowSelectButton="false"

															            SelectText="Edit Citizen"

												        				ShowEditButton="false"

												        				ShowCancelButton="false"

												        				ShowDeleteButton="false"

												        				DeleteText="Delete Citizen"

																		ValidationGroup="CitizenProf"

																		HeaderText="Action" HeaderStyle-Width="25" HeaderStyle-HorizontalAlign="Center" />	

																	<custom:DeleteButtonField ConfirmText="Remove this Citizen?" HeaderText="" HeaderStyle-Width="1" HeaderStyle-HorizontalAlign="Center" />

															 		

															 		<asp:BoundField

															 			HeaderStyle-Width="100" 

															 			HeaderText="     Citizen Name"

															 			ItemStyle-HorizontalAlign="Center" 

															 			DataField="citizen_name" >

															 		</asp:BoundField>

															 		

															 		<asp:BoundField

															 			HeaderStyle-Width="50"

															 			HtmlEncode="false" 

															 			HeaderText="     Citizen Breed" 

															 			ItemStyle-HorizontalAlign="Center"

															 			DataField="breed_name" >

															 		</asp:BoundField>

															 		<asp:ImageField

															 			HeaderText="Citizen Image"

															 			HeaderStyle-HorizontalAlign="Center"

															 			DataImageUrlField="citizen_image_url"

															 			ControlStyle-Width="80"

															 			ControlStyle-Height="80" />

															 		<asp:HyperLinkField

															 			HeaderText="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"

															 			Text="Edit Image"

															 			DataNavigateUrlFields="citizen_key"

															 			DataNavigateUrlFormatString="citizen_image_edit.aspx?id={0}" />

															 	</Columns>

															 	<RowStyle HorizontalAlign="Right" />

															 	</asp:Gridview>

															 	<asp:FormView

															 		id="frmCitizenDetail"

																		DefaultMode="Edit"

																		DataSourceID="srcCitizenDetails"

																		DataKeyNames="citizen_key"

																		AllowPaging="true"

																		Visible="true"

																		runat="server" >

														 				<EditItemTemplate>

																		 		<asp:DropDownList 

																					ID="drpPetSpecies" 

																					runat="server"

																					DataTextField="species_name" 

																					DataValueField="species_key"

																					DataSourceID="srcSpecies" 

																					SelectedValue='<%# Bind("citizen_species") %>'

																					AutoPostBack="true" 

																					OnSelectedIndexChanged="loadBreed_SelectedIndexChanged"

																					validationgroup="CitizenProf" 

																					TabIndex="2" >

																				</asp:DropDownList>

																				<asp:SqlDataSource ID="srcSpecies" Runat="Server" ConnectionString="<%$ ConnectionStrings:YPW %>" 

																					SelectCommand="SELECT [species_key],

																						[species_code],  

																						[species_name]

																						FROM [tblSpecies]

																						ORDER BY [species_code]" >

																				</asp:SqlDataSource>

																		 		<asp:DropDownList 

																					ID="drpPetBreed" 

																					DataTextField="breed_name" 

																					DataValueField="breed_key" 

																					DataSourceID="srcBreed"

																					SelectedValue='<%# Bind("citizen_breed") %>'

																					runat="server" 

																					Tabindex="4">

																				</asp:DropDownList>

																				<asp:SqlDataSource ID="srcBreed" Runat="Server" ConnectionString="<%$ ConnectionStrings:YPW %>" 

																					SelectCommand="SELECT [breed_key],

																						[breed_code],  

																						[breed_name],

																						[breed_species_key]

																						FROM [tblBreed]

																						ORDER BY [breed_code]" >

																				</asp:SqlDataSource>

														 				</EditItemTemplate>											 				

															</asp:FormView>

													 	<asp:Label	

													 		ID="lblOwnerKey"

													 		Visible="false"

													 		runat="server" />

<asp:SqlDataSource

    id="srcCitizen"

    ConnectionString="<%$ ConnectionStrings:YPW %>"

    SelectCommand="SELECT citizen_key, citizen_owner_key, citizen_name, citizen_breed, citizen_gender, citizen_image_url,

    				breed_key, breed_name 

    				FROM tblCitizen, tblBreed

	        		WHERE citizen_owner_key=@citizen_owner_key

	        		AND breed_key=citizen_breed"

	DeleteCommand="DELETE tblCitizen WHERE citizen_key=@citizen_key"

	    			Runat="server">

	<SelectParameters>

        <asp:ControlParameter Name="citizen_owner_key" ControlID="lblOwnerKey" />

    </SelectParameters>



</asp:SqlDataSource>

    

<asp:SqlDataSource

    id="srcCitizenDetails"

    ConnectionString="<%$ ConnectionStrings:YPW %>"

    SelectCommand="SELECT citizen_key, citizen_owner_key, citizen_name, citizen_species, citizen_breed, citizen_gender,     

	    				citizen_birthdate, citizen_image_url, citizen_image_label, citizen_country, citizen_occupation, citizen_pol_affil, 

	    				citizen_species_other, citizen_breed_other, citizen_country_other, citizen_occupation_other, citizen_polaffil_other,

	    				species_key, species_name, 

	    				breed_key, breed_name, breed_species_key,

	    				gender_key, gender_name, 

	    				country_key, country_name,    

	    				occupation_key, occupation_name, 

	    				polaffil_key, polaffil_name 

    				FROM tblCitizen, tblSpecies, tblBreed, tblGender, tblCountry, tblOccupation, tblPoliticalAffiliation	        			

    				WHERE citizen_key=@citizen_key 

    				AND species_key=citizen_species

    				AND breed_key=citizen_breed

    				AND gender_key=citizen_gender

    				AND country_key=citizen_country

    				AND occupation_key=citizen_occupation

    				AND polaffil_key=citizen_pol_affil" 

	UpdateCommand="UPDATE tblCitizen SET	citizen_name=@citizen_name, 

											citizen_species=@citizen_species, 

											citizen_breed=@citizen_breed, 

											citizen_gender=@citizen_gender, 

											citizen_birthdate=@citizen_birthdate,

											citizen_country=@citizen_country, 

											citizen_occupation=@citizen_occupation, 

											citizen_pol_affil=@citizen_pol_affil,

											citizen_species_other=@citizen_species_other, 

											citizen_breed_other=@citizen_breed_other, 

											citizen_country_other=@citizen_country_other, 

											citizen_occupation_other=@citizen_occupation_other, 

											citizen_polaffil_other=@citizen_polaffil_other

											WHERE citizen_key=@citizen_key"

    Runat="server">

    <SelectParameters>

    	<asp:Parameter Name="citizen_key" />

	</SelectParameters>



</asp:SqlDataSource>

Open in new window

0
Comment
Question by:dhynesok
2 Comments
 
LVL 8

Accepted Solution

by:
guvera earned 250 total points
Comment Utility
Hi,

  Using web services you can solve cascading drop down list problem
0
 

Author Closing Comment

by:dhynesok
Comment Utility
Disappointed that I got no usable solution.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now