I have an Edit page in my application that contains a DropDownList
.
This DDL is bound to an EntityDataSource that only shows the active "ProjectManagers".
In the case where the user is editing a record that is assigned to an "inactive" ProjectManger, an ArgumentOutOfRange
Exception is (rightfully) thrown by the DDL (because that Item wan't bound to the list, since it only binds "Active" ProjectManagers).
So, I need to add this item to the DropDownList
dynamically or at least add an "Inactive" item and then "select" that item in the code behind. (Although, adding an "Inactive" item would force the user to actually change the ProjectManager and that wouldn't be a good idea.)
I have tried handling the OnDataBinding
method with the following code:
protected void PreventErrorOnBinding(object sender, EventArgs e)
{
DropDownList theDropDownList = (DropDownList)sender;
theDropDownList.DataBinding -= new EventHandler(PreventErrorOnbinding);
theDropDownList.AppendDataBoundItems = true;
ListItem li = new ListItem(""<<Inactive>>", "0");
theDropDownList.Items.Insert(0, li);
try
{
theDropDownList.DataBind();
}
catch (ArgumentOutOfRangeException)
{
theDropDownList.SelectedValue = "0";
}
}
It seems to work, with one exception. My DropDownList
is "doubled". All of the Items are repeated. ie 1-8 then 1-8 again. It is somehow binding the items twice.
Also, (if I can get this working or find a better solution) I need get the (ProjectManagerID) value (the selected value or the actual column from the Entity Context). I have thought about handling the OnContextCreated
event of the EDS and getting it that way or would it be better (seems easier) to setup a local variable and in the markup do something like SelectedValue='<%# SaveValue(DataBinder.Eval(ContainerDataItem,"ProjectManagerID")) %>'
, then in the code behind I would save the "ProjectManagerID" to a locally defined variable (which I could then access in the "OnBinding" event code above...assuming that code fires after the Eval... and I think it would...).
I have also tried adding theDropDownList.Items.Clear() just before the DataBind call.
I can set a QuickWatch on theDropDownList.Items.Count and it is 14 before I leave this method, but then 28 items appear in the DropDownList. I dont get it....
Any thoughts to either of these problems?
Thanks for the help again folks! Shayne