Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Cascading DropDownLists in a FormView

Posted on 2010-11-08
2
Medium Priority
?
911 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 8

Accepted Solution

by:
guvera earned 500 total points
ID: 34091214
Hi,

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

Author Closing Comment

by:dhynesok
ID: 34205454
Disappointed that I got no usable solution.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

664 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