This is a migrated thread and some comments may be shown as answers.

SelectedValue is always empty

2 Answers 258 Views
ListBox
This is a migrated thread and some comments may be shown as answers.
JP
Top achievements
Rank 1
JP asked on 07 Feb 2012, 05:00 PM
Hi,

I'm using a ListBox for selecting an item.
If a button of the control is clicked, I want to fetch the SelectedValue.
The SelectedItem is not null (since one item is selected) but all properties of the SelectedItem (which shoud be set, like Value, Text, ImageUrl) are empty. In fact, all Items of the ListBox don't have their information anymore.
I add the items only once (when the ListBox is initially created) - I simple create a List of RadListBoxItem and add them to the ListBox.

This is the code I use to create the ListBox:

m_listBox = new RadListBox();
 m_listBox.ID = "ListBox1";
 m_listBox.SelectionMode = ListBoxSelectionMode.Single;
 
 if (!Initialized)
 {
    List<RadListBoxItem> items = LoadItems();
    foreach (RadListBoxItem radListBoxItem in items)
    {
       m_listBox.Items.Add(radListBoxItem);
    }
    m_listBox.SelectedIndex = 0;
    Initialized = true;
 }

The Initialized property is saved in viewstate because my control isn't added when the page loads initially but later in a workflow.

This is how I create an item:
RadListBoxItem item = new RadListBoxItem(text, id.ToString(CultureInfo.InvariantCulture));
item.ImageUrl = "include/img/Objects/"" +imageUr;
items.Add(item);

All values are added correctly but in the PostBack they are empty.

What could cause this behavior?

Thanks!

2 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 08 Feb 2012, 06:05 AM
Hello,

I have tried to reproduce the same but no avail. Here is the sample code that I have tried.
C#:
protected void button1_Click(object sender, EventArgs e)
   {
       String s1=RadListBox1.SelectedItem.Text;
       String s2 = RadListBox1.SelectedItem.Value;
   }

Thanks,
Princy.
0
JP
Top achievements
Rank 1
answered on 08 Feb 2012, 02:58 PM
I just found the problem: I created the ListBox during OnLoad (OnLoad calls EnsureChildControls) which was obviously too late. Calling EnsureChildControls in OnInit resolves the problem.
Tags
ListBox
Asked by
JP
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
JP
Top achievements
Rank 1
Share this question
or