Wednesday, December 17, 2008

Using dropdownlist in user control and to access the dropdownlist control value in .aspx page

A Common requirement we have would be to have a Dropdownlist of items which would be common across all the pages (top navigation or in the left navigation).

Retrieving the selected item in a dropdownlist which resides in the same page, is pretty straight forward dropdownlist1.selecteditem.value.

However, when it is in a usercontrol, its pretty difficult to retrieve it since you will get the "Object Reference not set to an instance" error if you try the normal method. Even if you create an instance of the usercontrol and try to access its dropdownlist, you will get the above error.

The following code demonstrates how to overcome this problem.

UserControl objCtrl = ((UserControl)(FindControl("Id of the Usercontrol as declared in the container page")));
DropDownList ddl = ((DropDownList)(objCtrl.FindControl("Id of the Dropdownlist control in the usercontrol")));

Response.Write(ddl.SelectedItem.Value);
Thats it and you can access the value.

Cheers and Happy Programming!

No comments: