Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When something is selected in the ListBox1 the selectedindexchanged event fires however listbox1.selecteditem/index/value is null. How can I get the SelectedItem ?

C#
   protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
   {
       var row = ListBox1.SelectedItem.Text;
       var date = DateTime.ParseExact(row,"yyyy-MMMM", CultureInfo.InvariantCulture);
       ChangeMonthViewOnGridView1(date.Year, date.Month);
   }


<asp:ListBox ID="ListBox1" runat="server"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" Width="258px"
AutoPostBack="True" ></asp:ListBox>


What I have tried:

using breaking point for debugging. I can't see no trace of signs of the change. tried with dropdownlist too there the selecteditem remains the first one.
Posted
Updated 16-Feb-17 22:19pm
Comments
Karthik_Mahalingam 16-Feb-17 22:48pm    
how you are binding the data?
show the code.
[no name] 17-Feb-17 16:35pm    
IEnumerable<datetime> months = monthsBetween(startingMonth, currentMonth).Reverse();

List<string> formattedMonths = new List<string>();

foreach (var month in months)
{
formattedMonths.Add(month.ToString("yyyy-MMMM"));
}
ListBox1.DataSource = formattedMonths;
ListBox1.DataBind();
Karthik_Mahalingam 17-Feb-17 22:43pm    
have tested ur code, it works fine.. you are missing something and you are not telling.
Maciej Los 17-Feb-17 4:26am    
Replace var row = ListBox1.SelectedItem.Text; with var row = ListBox1.SelectedItem.Value;
[no name] 17-Feb-17 16:37pm    
listbox1.selected....... all of them have null value when I check it with vs debugger.

1 solution

replace your code

<asp:ListBox ID="ListBox1" runat="server"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" Width="258px"
AutoPostBack="True" ></asp:ListBox>


with

<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
                <asp:ListItem>2017-January</asp:ListItem>
                <asp:ListItem>2017-February</asp:ListItem>
                </asp:ListBox>



and try. this is working for your code behind
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900