Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selected Item of a listbox 1

Status
Not open for further replies.

FederalProgrammer

Programmer
Jul 2, 2003
318
CA
this must be super easy for one of u to answer:

I have a list box.
I add items to this listbox dynamically.
I capture the "SelectedIndex_Changed" event of this listbox.
The event is raised and handled once the user clicks on the listbox to select one of the items.
I've made sure AutoPostBack is set to true.

The problem is this:
When the event is handled myListbox.SelectedIndex = -1!! We all know what that means! Also, whenever the user clicks on the listbox, the item inside the listbox doesn't get selected?!!




---------------
 
Try to use the selected item instead of the selectedindex. e.g.
Code:
ListBox1.SelectedItem.Value

----------------------------------------------------------------------

Need help finding an answer?

Try the search facilty ( or read FAQ222-2244 on how to get better results.
 
Sounds like it's getting reloaded when the SelectedIndexChanged event get fired.
Page_Load ....
if(!IsPostBack)
{
LoadMyListBox()
}
 
Thanx for the replies....

Veep:
yeah I think I need to do something to that effect. That's exactly my question though... how do I implement this,
loadMyListbox() function? Do I need to Cache the list box? Is there a better way to do this... Even if I cache it, how do I get the eventhandler to work?

ca8msm :
SelectedItem will do the same... selectedValue will do the same... the problem is that, the item in the list box doesn't get selected at all




---------------
 
Here's an example of loading a DropDownList (same difference) that posts back when it gets changed. I do not call LoadJobSelector on the SelectedIndexChanged event because I want it to retain it's selected value via ViewState:
Code:
private void Page_Load(object sender, System.EventArgs e)
		{
			if(!IsPostBack)
			{
				LoadJobSelector();
			}
		}
		private void LoadJobSelector()
		{
			string strSql = "o_sp_Load_Run_Job";
			SqlDataReader reader = SqlHelper.ExecuteReader(conn,CommandType.StoredProcedure,strSql);
			if(reader.HasRows)
			{
				while(reader.Read())
				{
					ListItem li = new ListItem();
					li.Value = reader["JobID"].ToString();
					li.Text = reader["JobID"].ToString() + "   |   " +
						string.Format("{0:d}",reader["Scheduled"]) + "   |   " +
						reader["JobName"].ToString();
					ddlSelectJob.Items.Add(li);
				}
				ddlSelectJob.Items.Insert(0,"--Select Job--");
			}
			else
			{
				ddlSelectJob.Items.Insert(0,"*** No Jobs To Display ***");
			}
		}
 
Sorry, it got a little messy with the VSNET indentation.
 
Right on... thanx,
but I guess, it's the ViewState that I have to worry about then... so how do I use ViewState to get the selectedItem of a listbox...

by the way my list box gets loaded by the user... user fills up a bunch of text boxs and clicks on add to create an item in the listbox... then I want the user to select an item from the listbox... As you said, I should do this by using ViewState... I am new to ASP.NET (i've done a lot of desktop application development though)... how do I use ViewState...

thanx so much for your help so far!!!!



---------------
 
list box gets loaded by the user"
By JavaScript or a postback everytime???

ViewState runs by default, and if you use the listbox in a normal situation, most of what you need is taken care of for you.
 
thanx for the reply,
I handle it through postback...
1) A button gets clicked...
2) its handler reads user inputs...
3) it creates an object...
4) adds the object to the listbox...
the items are displayed in the listbox correctly...

it's just that as the user clicks on the listbox items, they don't get selected!? WEIRD, isn't it? in windows application, as user clicks on an item of a listbox, the selected item gets highlighted...



---------------
 
I just did a small example and it worked just fine. Are you sure your going into the postback. Can you break in the SelectedIndexChanged. You should be able to put something like this inside that procedure

Response.Write(ListBox1.SelectedValue)

 
ok, here's what I have:

Listbox1.Autopostback = True

Private Sub Listbox1_selectedIndexChanged(o as object, e as eventargs) handles listbox1.selectedIndexChanged
'some code
end sub

I put a break point by some code and when I try the following:
? me.Listbox1.SelectedIndex
I get -1;

When I click on my listbox without setting the breakpoint, my items in the list box don't even get highlighted... no wonder selectedIndex = -1



---------------
 
I can show you the exact code in 7 hours... I'm at work and this code is on my home computer!
Please don't forget me!! I really wanna be able to do this!

Thanx a million!!!!



---------------
 
I don't do anything too special in my Page load:

Code:
If (not IsPostBack)
   me._lstSource = new someObject
   me.cache.add("lstItems", me._lstSource, ...)
Else
   Me._lstSource = Me.Cache.Item("lstItems")
End if

Me.lst.DataSource = Me._lstSource.DataSource
Me.lst.DataValueField = Me._lstSource.Value
Me.lst.DataTextField = Me._lstSource.DisplayMember
Me.lstBandMembers.DataBind()

Please remember, "SomeObject" is an object with a couple of hashtables.
ht1:
key = GUID of the object to be added to listbox
Value = the object (it can be anything, an employee, a bank account, etc)

ht2:
key = GUID of the object to be added to listbox
Value = the Text (this is the text to be displayed in the listbox)




---------------
 
Hay,
Ok, I added a bunch of stuff at design time to my list box, it worked like a charm... it may have to do w/ the way I'm adding items to my listbox then...

I am trying to add objects to my listbox (rather than simple text)... is that possible in web applications? I want to add, say, an employee object to my listbox and use emplyee's first name as the text to be displayed on the listbox.... is this doable??



---------------
 
About Your First Method...
Your rebinding the List every postback, that's why it doesn't work. You don't have to do that because ViewState will do it for you. That's the great part about ASP.NET. Just bind it in (Not PostBack) and forget about it. Try this

If (not IsPostBack)
me._lstSource = new someObject
me.cache.add("lstItems", me._lstSource, ...)
Me.lst.DataSource = Me._lstSource.DataSource
Me.lst.DataValueField = Me._lstSource.Value
Me.lst.DataTextField = Me._lstSource.DisplayMember
Me.lstBandMembers.DataBind()
Else
Me._lstSource = Me.Cache.Item("lstItems")
End if


You can only add strings and ListItems to Listbox.Items.

You can bind to any class that implements IList. So if you made a collection of employees you could bind to that.
Looks something like
Me.lst.DataSource = Me._employeeList
Me.lst.DataValueField = "ID"
Me.lst.DataTextField = "FirstName"
Me.lstBandMembers.DataBind()


If you want to add objects to your list one at a time you could just do this

Me.lst.Add(employee.Name)
 
u're an all star!!!! thanx a million... i'll try removing the databind tonight, and let you know!

In regards to adding objects to the list box,I didn't know about IList... i'll look into it;

If I add employee.name to my listbox, then I will loose all the other properties of my employee right? consider this situation:
I have a bunch of emplyee names in my listbox. When user selects an employee, I will show all of emplyee info: name, birthdate, overtime, payrate, etc. These are all properties of the employee object. So just adding the name won't do.
What I've done so far, is I've implemented my own collection of "MyListBoxItems". An instance of MyListBoxItems, has
GUID,
object,
text
as its properties. Then when I add items to my listbox, I use the GUID as the value of the value field and Text as text field. Now when the user selects an item from my listbox, I can lookup its GUID in my collection and get the object representing the selected GUID ;)

I hope I didn't re-invent the wheel... I didn't know about IList... I'll look it up!!

Once again thanx a million for your help!!



---------------
 
Yup, you were right...
Databind is only necessary the first time... not on the post back...
However I still have to assign the Datasource to the listbox... final sol'n:

Code:
If (not IsPostBack)
   me._lstSource = new someObject
   me.cache.add("lstItems", me._lstSource, ...)
   Me.lst.DataSource = Me._lstSource.DataSource
   Me.lst.DataValueField = Me._lstSource.Value
   Me.lst.DataTextField = Me._lstSource.DisplayMember
   Me.lstBandMembers.DataBind()
Else
     Me._lstSource = Me.Cache.Item("lstItems")
   Me.lst.DataSource = Me._lstSource.DataSource
   Me.lst.DataValueField = Me._lstSource.Value
   Me.lst.DataTextField = Me._lstSource.DisplayMember

End if




---------------
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top