c# getting selected value from list box

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • semomaniz
    Recognized Expert New Member
    • Oct 2007
    • 210

    #1

    c# getting selected value from list box

    I have a list box that has a list of roles defined. List of roles are binded to the list box in page load event. I am trying to retrieve the selected role from the text box but i am getting a null reference error even though one of the item is selected. below is the code that gives me null reference.


    Code:
     String role = lstRole.SelectedItem.ToString();
    Code:
     Label1.Text = role;

    I even tried using the code below and all i get is null value. seems like it not selecting any thing form the list box.

    Code:
    String role = lstRole.SelectedValue;
    Does any one have any idea what is going on??

    Thanks in advance.
  • harshmaul
    Recognized Expert Contributor
    • Jul 2007
    • 490

    #2
    hi,
    please show me how you are binding the data to the list.
    A common problem i have is that on the page load it binds the data again therefore clearing the selection i made.

    Comment

    • kunal pawar
      Contributor
      • Oct 2007
      • 297

      #3
      Please used property
      selectedItem.Te xt for text and SelectedItem.va lue for getting values

      Comment

      • semomaniz
        Recognized Expert New Member
        • Oct 2007
        • 210

        #4
        Code:
        if (!Roles.IsUserInRole(User.Identity.Name, "Admin"))
                    {
                        btnSubmit.Enabled = false;
                        btnclear.Enabled = false;
                        lblerr.Text = " You donot have permission to create accounts ";
        
                    }
                    else
                    {
                        
                        lstRole.DataSource = Roles.GetAllRoles();
                        lstRole.DataBind();
                    }
        This is how i am binding the data to the list box. I tried using

        Code:
         Label1.text = lstRole.SelectedItem.Text
        it still gives me null reference exception.

        Comment

        • semomaniz
          Recognized Expert New Member
          • Oct 2007
          • 210

          #5
          got the problem solved. I forgot to check for post back. That was the reason why the value selected was being lost . Thank you for all your help.

          cheers!!!!!!!!! !!!

          Comment

          Working...