Tuesday, March 13, 2012

Setting the SelectedValue Drop Down List which is DataBound.

I have a custom control which contains one drop down list. The drop down list is populated using a SqlDataReader and contains a list of colours (e.g. Red, Green, Blue).

When the page loads I would like to be able to set the SelectedValue of the list to a colour value (e.g. Green).

The custom control has properties SelectedValue and SelectedIndex which expose the two values from the drop down list control.

The custom control Page_Load event will only bind the data to the drop down "If Not Page.IsPostBack".

The control renders correctly. However, when I try to set the selected value using either SelectedValue or SelectedIndex properties, the following error occurs:

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

The web form Page_Load calls a sub which attempts to set the property.

Any ideas why this is happening or how to solve this problem?How are you referencing your user control from your page? If you are using a DIM statement then that is the problem... you need to do something like this:

Protected MyControl1 As MyProject.MyControl

Where MyControl1 is the same exact name as the control that you have put on your page and myproject.mycontrol points to the control.

Hope this helps...I used to get alot of those errors myself :)

Thanks,
MajorCats
I believe you can call myDropDown.Items(itemIndex).Selected = True. Your current method should be working, though; can you show us some code?

Another way to get this working would be to useEasyListBox instead of the regular dropdown list; SelectedValue and SelectedIndex always work, and you have a ton of other features at your disposal as well.
Could you post some of the code you're using? At the least, the line that is causing the error? It sounds like you're trying to access an object that hasn't been initialized. It'd be easier to troubleshoot with a little more information.

0 comments:

Post a Comment