selectedIndex is lost during postbacks - ASP.NET

后端 未结 9 1780
北海茫月
北海茫月 2021-01-13 06:35

I have a list box control:




The code behind resembles:

<         


        
相关标签:
9条回答
  • 2021-01-13 07:19

    Databinding DropDownLists/ListBoxes is painful, because they often bind to the wrong values.

    I've given up on using DataBind(), and just resort to using a Foreach loop:

    foreach (Item i in DataSet)
    {
         listBox.Items.Add(etc);
    }
    
    0 讨论(0)
  • 2021-01-13 07:22

    What's the output of the foo() function call?

    Populating manually the list box you can set indexes to whatever you want (all 0 for example) - so the same thing can happen setting a given dataSource under certain circumstances (one that specifies indexes I suppose). If all the item indexes are 0 the result is that the SelectedIndexChanged event is not raised (index does not change!) and everything is messed up: on post-back selection will go back to the first item in the list.

    This would explain it - I cannot think of anything else - it is working fine for me on .NET 2.0 I am using an ArrayList with strings to populate the listBox.

    The only way I can reproduce your issue is setting all indexes to 0.

    I'd say add a watch to the ListBox and check the indexes at runtime to make sure they're not all zeroes.

    0 讨论(0)
  • 2021-01-13 07:25

    Load the data in the Page_Init instead of the Page_Load. The data has to be filled during the Page_init to be available in the PostBack.

    0 讨论(0)
提交回复
热议问题