Click to See Complete Forum and Search --> : ListBox.SelectedItem ???


Toot
February 28th, 2005, 09:05 AM
Hi gurus, just starting out on ASP.NET so excuse my obvious lack of experience...

How do I know what item is selected in a listbox on an ASP.NET web form? I've tried attaching to the SelectedIndexChanged event. First time around, it was being called when the user submitted the form and the listbox's SelectedIndex value was always -1 so I tried changing the Autopost property on the form to true which now means that the event occurs when the index is changed ... but SelectedIndex is still always -1. So I've tried to add a piece of client code which captures the OnSelectedItemChanged event and sets another hidden input on the form so that the server can pick it up. But now I can't work out how to get at that value from the server code.

Clearly I'm missing something pretty basic - please put me out of my misery!

Can someone provide a sample page that contains a listbox and a submit button that will show which item was selected in the listbox?

PS: I'm writing in C# but I won't be picky about sample code :) .

Thanks very much, you're great.
T

mmetzger
February 28th, 2005, 10:04 AM
Here's the example from MSDN:


<%@ Page Language="C#" AutoEventWireup="True" %>

<html>
<head>

<script language="C#" runat="server">

void SubmitBtn_Click(Object sender, EventArgs e)
{
if (ListBox1.SelectedIndex > -1)
Label1.Text="You chose: " + ListBox1.SelectedItem.Text;
}

</script>

</head>
<body>

<h3>ListBox Example</h3>

<form runat=server>

<asp:ListBox id="ListBox1"
Rows="6"
Width="100px"
SelectionMode="Single"
runat="server">

<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>

</asp:ListBox>

<asp:button id="Button1"
Text="Submit"
OnClick="SubmitBtn_Click"
runat="server" />

<asp:Label id="Label1"
Font-Name="Verdana"
Font-Size="10pt"
runat="server"/>

</form>

</body>
</html>


Now, that sounds pretty much like what you're describing, so I bet I know what the problem is. Where are you initializing the listbox, within the Page_Load method? If so, you need to make sure to add something like:


void Page_Load (Object sender, EventArgs e)
{
if (!IsPostBack)
{
// Initialize / Databind Listbox
}
}


Otherwise, what happens is the objects are reset (hence the -1 selected index) before it tries to read your data.

PeterBrunone
January 9th, 2007, 04:47 PM
Another problem might be that the listbox is in multi-select mode...? The native asp:ListBox doesn't give you all the selections in the SelectedValue property (like some (http://easylistbox.com/demoMulti.aspx?rl=cgf) third-party controls do).