Selected Item in Dropdownlist in an Usercontrol

Last post 06-24-2009 3:07 AM by z0333. 2 replies.

Sort Posts:

  • Selected Item in Dropdownlist in an Usercontrol

    11-17-2004, 7:41 AM
    • Star
      12,063 point Star
    • ranganh
    • Member since 02-11-2004, 11:35 PM
    • India
    • Posts 2,428


    Hi,

    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.

    NOTE: This is not the only way and there are other ways like creating an object of the usercontrol and accessing. However, this method is relatively simple.
    regards,
    Harish

    http://geekswithblogs.net/ranganh
  • Re: Selected Item in Dropdownlist in an Usercontrol

    06-05-2009, 1:19 PM
    • Member
      4 point Member
    • mcupryk
    • Member since 06-08-2007, 7:34 PM
    • Posts 9

    This one is not working for me.

  • Re: Selected Item in Dropdownlist in an Usercontrol

    06-24-2009, 3:07 AM
    • Member
      52 point Member
    • z0333
    • Member since 04-29-2007, 3:53 AM
    • Posts 83

    You can add a public property to the user control that expose dropdownlist1.selecteditem.value:

     

    Public ReadOnly Property SelectedValue() As String

                Get

                    Return dropdownlist1.selecteditem.value

                End Get

     End Property

Page 1 of 1 (3 items)