I have a ListBox (I'll call it listBoxEmployees) that is bound to an ObjectDataSource (I'll call odsListBoxEmployees).
<asp:ListBox ID="listBoxEmployees" runat="server"
AutoPostBack="true"
DataSourceID="odsListBoxEmployees"
DataTextField="EmployeeName"
DataValueField="EmployeeID"
onselectedindexchanged="listBoxEmployees_SelectedIndexChanged"
ondatabound="listBoxEmployees_DataBound">
</asp:ListBox>
It displays Employee Name as Text and stores EmployeeID as Value in the list.
Then I have a FormView which is bound to another ObjectDataSource (I'll call it odsEmployee) which retrieves an individual record when an item is selected in the ListBox control. Below is the FormView definition:
<asp:FormView
ID="fvEmployee"
runat="server"
DataKeyNames="EmployeeID"
DataSourceID="odsEmployee"
>
Below is the ODS definition:
<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>
What I want to do after inserting a record from the FormView is to add the newly inserted record in the ListBox control and highlight it by making it the selected item. Below is how to achieve this:
Handle the Inserted event of odsForm as follows:
protected void odsForm_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
{
ViewState["EmployeeID"] = e.ReturnValue;
}
This will store the employee id of the new inserted record in the view state.
And then handle the DataBound event of the ListBox 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.
It works great.
Sharing the joy of coding in C#, Asp.Net MVC, JavaScript, HTML5, TDD/BDD, DDD and anything code related.
Subscribe to:
Post Comments (Atom)
About Cullen
- Software Engineer/Architect
- Christian, Father, Software Developer/Architect who enjoys technology and using it to make people's lives easier!
No comments:
Post a Comment