Below is the definition of the ListBox:
<asp:ListBox ID="listBoxEmployees" runat="server"
AutoPostBack="true"
DataSourceID="odsListBoxEmployees"
DataTextField="EmployeeName"
DataValueField="EmployeeID"
onselectedindexchanged="listBoxEmployees_SelectedIndexChanged"
ondatabound="listBoxEmployees_DataBound">
</asp:ListBox>
Below is the definition of the FormView:
<asp:FormView
ID="fvEmployee"
runat="server"
DataKeyNames="EmployeeID"
DataSourceID="odsEmployee"
oniteminserted="fvEmployee_ItemInserted"
>
Below is the definition of the Object Data Source:
<asp:ObjectDataSource
ID="odsEmployee"
runat="server"
TypeName="Employees"
SelectMethod="SelectOne"
InsertMethod = "Insert"
UpdateMethod = "Update"
DeleteMethod = "Delete"
ConflictDetection="OverwriteChanges"
oninserted="odsEmployee_Inserted"
ondeleting="odsEmployee_Deleting"
>
<SelectParameters>
<asp:ControlParameter Name="EmployeeID" Type="Int32" Direction="Input" ControlID="listBoxEmployees" PropertyName="SelectedValue" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="EmployeeName" Size="80" Direction = "Input" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" Direction="Input" />
<asp:Parameter Name="EmployeeName" Size="80" Direction = "Input" Type="String" />
</UpdateParameters>
</asp:ObjectDataSource>
Handle Deleted event of the ODS so before the record is deleted in the FormView, we'll store the next item in the ListBox in view state as follows:
protected void odsEmployee_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
{
//if there are more one items in the list
if (listBoxEmployees.Items.Count > 1)
//if the record to be deleted is not the last one in the list
if (listBoxEmployees.SelectedIndex < listBoxEmployees.Items.Count-1)
{
//store the next item's value
ViewState["EmployeeID"] = listBoxEmployees.Items[++listBoxEmployees.SelectedIndex].Value;
}
else
//if it is the last one, then store the previous item's value
ViewState["EmployeeID"] = listBoxEmployees.Items[--listBoxEmployees.SelectedIndex].Value;
}
The code above is self explanatory.
Next handle the DataBound event of the ListBox control as follows:
protected void listBoxEmployees_DataBound(object sender, EventArgs e)
{
if (listBoxEmployees.Items.Count > 0)
if (ViewState["EmployeeID"] != null)
{
listBoxEmployees.SelectedValue = ViewState["EmployeeID"].ToString();
}
else listBoxEmployees.SelectedIndex = 0;
ViewState.Remove("EmployeeID");
}
This will set the SelectedValue of the ListBox to the value in the view state. After we used the value in the view state, we remove it.