T...">

SelectedIndex gets lost during postbacks - ASP.NET

I have a list control:


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

The code behind is like:


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 message back (when the user makes a choice in the list), the selection always “jumps” to the first element in the list, so the index variable in my callback function is always 0.

Sounds like it might be a problem with the presentation of the views? How can I fix this so that the allocation index remains through postback?

No ajax, this is .NET 1.0.

Thanks.

EDIT 1 JohnIdol took a step closer to me, if I switch the data source from my original DataTable to an ArrayList, then everything will work correctly ... what can cause this?

2 , DataTable , , , ... ,

+5
9

foo()?

, , (, , 0) - , (, , , ). 0, , SelectedIndexChanged ( !), : .

- - .NET 2.0. ArrayList listBox.

- 0.

, ListBox , , .

+2

real - . page_load, , . , Page_Init.

+10

, 0. , item.value item.text . .

+2

DropDownLists/ListBoxes , .

DataBind() Foreach:

foreach (Item i in DataSet)
{
     listBox.Items.Add(etc);
}
+1

Page_Init Page_Load. Page_init, PostBack.

+1

, . . :

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

, , ?

protected void lbox_SelectedIndexChanged(object sender, EventArgs e)
{
    int index = lbox.selectedIndex;
}
0

. foo() ?

: , OnInit ( , GET). base.OnInit(...), (, , , . , , , ).

-, , ViewState. : TRULY ViewState

0

- , OnInit / . , , , on-change? , - viewstate!

-1

, , , . :

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

, , ViewState . ViewState , .

-2

All Articles