ListBox PROBLEM in User control

P

Pierre

Hello,

I'm trying to develop a simple Web User Control that contains two list
boxes, Add and Remove buttons. This User Control transfers the selected
items from left list box to right list box and vice-versa, depending on the
button clicked. The SelectionMode of both list boxes is "Multiple" and
AutoPostBack is set to false.

Here is the simple process:
string strItemsToKeep = "";
// Collect all items selected from lbLeftList list box.
foreach( ListItem item in lbLeftList.Items )
{
if( item.Selected )
{
lbRightList.Items.Add( item.Text );
}
else
{
strItemsToKeep = strItemsToKeep + item.Text + ";";
}
}
Then after the loop, I process the string and load it back to the left list
box. This works great within a simple aspx page.

But, here's my problem:
In a User Control ascx page, in the Code Behind, for each item retrieved
from lbLeftList, I can see the data in each item.Text but the item.Selected
is always false.

After searching on the Web, I tried the following:
System.Web.UI.UserControl UserControl;
UserControl =
(System.Web.UI.UserControl)Parent.FindControl("Double_list_control1");
//which is the name of the User Control in the parent page.

System.Web.UI.WebControls.ListBox lb;
lb = (System.Web.UI.WebControls.ListBox)UserControl.FindControl("lbLeftList");

I thought that I could finally retrieve the correct information but, once
again, I have the same problem: the lb.Items[0].Selected (which is the one I
selected) is also set to false.

I really do not understand what is going on. If somebody can help me it
will greatly be appreciated.

Thank you very much.
 
R

recoil

Several things.
your user control should be implementing INamingContainer. Append it to
your class definition as such
public class MyUserControl : WebControl, INamingContainer

Then make sure that the control is created around the OnInit event. If
need be You can override OnInit and create all of your control's in
there.
Then Set the ID's of the control.
then call base.OnInit();

If you follow those 3 steps almosdt ALL of your problems should
disappear.
Then just remember that you should not try accessing the varaibles
until AFTER the LoadViewState has been called which means that you can
either Overload LoadViewState and call base.LoadViewstate and then
perform your actions there or you can override OnLoad and stick your
logic code there.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top