By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,934 Members | 1,677 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,934 IT Pros & Developers. It's quick & easy.

c# getting selected value from list box

Expert 100+
P: 210
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.


Expand|Select|Wrap|Line Numbers
  1.  String role = lstRole.SelectedItem.ToString(); 
Expand|Select|Wrap|Line Numbers
  1.  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.

Expand|Select|Wrap|Line Numbers
  1. String role = lstRole.SelectedValue;
Does any one have any idea what is going on??

Thanks in advance.
Feb 7 '08 #1
Share this Question
Share on Google+
4 Replies


harshmaul
Expert 100+
P: 490
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.
Feb 7 '08 #2

kunal pawar
100+
P: 297
Please used property
selectedItem.Text for text and SelectedItem.value for getting values
Feb 8 '08 #3

Expert 100+
P: 210
Expand|Select|Wrap|Line Numbers
  1. if (!Roles.IsUserInRole(User.Identity.Name, "Admin"))
  2.             {
  3.                 btnSubmit.Enabled = false;
  4.                 btnclear.Enabled = false;
  5.                 lblerr.Text = " You donot have permission to create accounts ";
  6.  
  7.             }
  8.             else
  9.             {
  10.  
  11.                 lstRole.DataSource = Roles.GetAllRoles();
  12.                 lstRole.DataBind();
  13.             }
  14.  
This is how i am binding the data to the list box. I tried using

Expand|Select|Wrap|Line Numbers
  1.  Label1.text = lstRole.SelectedItem.Text
it still gives me null reference exception.
Feb 8 '08 #4

Expert 100+
P: 210
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!!!!!!!!!!!!
Feb 8 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.