selectedIndex is lost during postbacks - ASP.NET

2019-02-17 12:35发布

I have a list box control:


<asp:ListBox runat="server" id="lbox" autoPostBack="true" />

The code behind resembles:


private void Page_Load(object sender, System.EventArgs e)
{
    lbox.SelectedIndexChanged+=new EventHandler(lbox_SelectedIndexChanged);
    if(!Page.IsPostBack)
    {
        LoadData();     
    }
}
private LoadData()
{
    lbox.DataSource = foo();
    lbox.DataBind();
}
protected void lboxScorecard_SelectedIndexChanged(object sender, EventArgs e)
{
    int index = (sender as ListBox).selectedIndex;
}

My problem is that when my page receives a post back (when a user makes a selection in the listbox), the selection always "jumps" to the first item in the listbox, so that the index variable in my callback function is always 0.

Seems like this may be a viewstate problem? How can I fix it so that the selection index remains through the postback?

There is no ajax going on, this is .NET 1.0.

Thanks.

EDIT 1 JohnIdol has gotten me a step closer, If I switch the datasource from my original DataTable to an ArrayList, then everything work properly...what would cause this?

Edit 2 It turns out that my DataTable had multiple values that were the same, so that the indexes were treated as the same as all items with the same value...thanks to those who helped!

9条回答
地球回转人心会变
2楼-- · 2019-02-17 13:30

Works for me too. Does your foo() return the same values every time?

Just as a side note: if possible, you should really do your databinding in OnInit (every time, not just on GETs). If you do it before the call to base.OnInit(...), the contents of your listbox won't have to be serialized and deserialized to and from viewstate and sent across the wire to the client (yes, you will be hitting the database more, but you'll be hitting a system which is located on your local subnet, or even on the same machine. Moreover, the database will likely cache the result).

If you want to build high-performance websites, you need to take a close look at the way you use ViewState. I highly recommend this article: TRULY Understanding ViewState

查看更多
Ridiculous、
3楼-- · 2019-02-17 13:35

if your listbox items are same then selected index will get set to 0.To rectify it, set different values to item.value and let item.text remains the same..then selected index will be displayed properly.

查看更多
霸刀☆藐视天下
4楼-- · 2019-02-17 13:36

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);
}
查看更多
登录 后发表回答