My issue is I have a Dropdownlist with its selected value being populated by a querystring. I have a home page and a products page on my site. on the homepage you can click an image that contains the query to populate the dropdownlist, and it works fine,
but if you click on the Products tab to view the products page with the same dropdownlists and all i get this error:
A critical error has occurred.Object reference not set to an instance of an object. Since my code is in the databound of DDL1 I need to ignore this code if you
just click the Products tab from the site, that does not contain a query. I am not sure how to go about this.
I would appreciate any help.
here is my code.
ProtectedSub
DropDownList1_DataBound(sender AsObject,
e AsEventArgs)
Handles
DropDownList1.DataBound ForEach
item AsListItemIn
DropDownList1.Items If
item.Value = Request.QueryString("id").ToString()
Then item.Selected =True EndIf Next DropDownList2.Items.Clear()
DropDownList2.DataBind() EndSub
jplotz
Member
1 Points
2 Posts
Query String and Dropdownlist help
Jun 12, 2012 03:36 PM|LINK
My issue is I have a Dropdownlist with its selected value being populated by a querystring. I have a home page and a products page on my site. on the homepage you can click an image that contains the query to populate the dropdownlist, and it works fine, but if you click on the Products tab to view the products page with the same dropdownlists and all i get this error: A critical error has occurred.Object reference not set to an instance of an object. Since my code is in the databound of DDL1 I need to ignore this code if you just click the Products tab from the site, that does not contain a query. I am not sure how to go about this.
I would appreciate any help.
here is my code.
Protected Sub DropDownList1_DataBound(sender As Object, e As EventArgs) Handles DropDownList1.DataBound
For Each item As ListItem In DropDownList1.Items
If item.Value = Request.QueryString("id").ToString() Then
item.Selected =True
End If
Next
DropDownList2.Items.Clear()
DropDownList2.DataBind()
End Sub
Mudasir.Khan
All-Star
15346 Points
3142 Posts
Re: Query String and Dropdownlist help
Jun 12, 2012 04:12 PM|LINK
try placing a null check for example
if Request.QueryString("id") isnot nothing andalso not string.isNullOrEmpty(Request.QueryString("id"))
For Each item As ListItem In DropDownList1.Items
If item.Value = Request.QueryString("id").ToString() Then
item.Selected =True
End If
Next
end if
sushanth009
Contributor
6243 Points
1168 Posts
Re: Query String and Dropdownlist help
Jun 12, 2012 04:37 PM|LINK
First try checking if the Query String is not Nott... Only if its Not Null then Convert it to string
This must be the source of the exception
jplotz
Member
1 Points
2 Posts
Re: Query String and Dropdownlist help
Jun 12, 2012 04:43 PM|LINK
Thanks Mudasir, This works perfectly!