views:

216

answers:

3

Where in the event life cycle should I set the ListBox.SelectedIndex if the Listbox is contained within a FormView? What I'm trying to do is increase the SelectedIndex by 1 which makes it move from item to item whenever a user clicks on a submit button.

A: 

In the OnClick event handler for the submit button.

You could find the ListBox control from the controls list of the FormView and then increase the selectedIndex

something like this:

    public void Button1_Click(object sender, EventArgs e)
    {
        foreach (Control c in fv1.Controls)
        {
            if (c is ListBox)
            {
                ListBox lbx = c as ListBox;
                ++lbx.SelectedIndex;
            }
        }
    }
sean717
I have already tried this on the FormView_Inserted event of the FormView Container since I'm using the in-built FormView command buttons. This did not work. The ListBox loses the SelectedIndex after postback. Any ideas?
jmm312
Post your aspx if possible.
sean717
A: 

Well if you want to increase the selectedindex when a button is clicked, what about increasing it in the button click event? Where are you trying to set it that you're having problems?

DougJones
+1  A: 

You have to use FindControl to access the listbox and then increment the value. The following code would go in the button submit event:

ListBox myListBox = myFormView.FindControl("myListBox") As ListBox;
if (myListBox != null) {
    myListBox.SelectedIndex++;
}
Jason Berkan
I have already tried this on the FormView_Inserted event of the FormView Container since I'm using the in-built FormView command buttons. This did not work. The ListBox loses the SelectedIndex after postback. Any ideas?
jmm312
Are you rebinding to the listbox on a postback?
Jason Berkan
The ListBox is attached to an ObjectDataSource so I suppose it is rebound automatically by .NET on postback.
jmm312