ASP.NET OnDataBinding event for EditItemTemplate DropDownList

asp.netdata-bindingdatasourcedetailsviewevents

I have a dropdownlist control in an edititemtemplate for a details view defined like this:

<asp:TemplateField HeaderText="Primary Use">
 <EditItemTemplate>
  <asp:DropDownList ID="ddlPrimaryUseEdit" runat="server" OnDataBinding="DropDownList_DataBinding"
      SelectedValue='<%# Bind("PrimaryUse") %>' ToolTip="Primary Use">
   <asp:ListItem Value="">Unknown</asp:ListItem>
   <asp:ListItem>Manufacturing Facilities</asp:ListItem>
   <asp:ListItem>Residential</asp:ListItem>
   <asp:ListItem>VSSM Office</asp:ListItem>
   <asp:ListItem>Engineering / Office / Warehouse</asp:ListItem>
   <asp:ListItem>Vacant / Surplus Land</asp:ListItem>
  </asp:DropDownList>
 </EditItemTemplate>

I have a datasource definded as a query to my database that has a column named "PrimaryUse". Sometimes there can be a value in the PrimaryUse column that isn't listed as one of the dropdownlist items and so my application crashes when trying to bind the dropdownlist's selectedvalue to that field. I'm trying to create code in the edititemtemplate's OnDataBinding event that will check if the value being returned from the datasource is a valid value listed as an item in the dropdownlist options. My problem is that I'm not sure how to get the datasources fieldvalue for that column in the behind code. Is this possible? Is so, can some one give me an example or point me in the direction on how to do this?

So, in the OnDataBinding event for the edititemtemplate listed above, I would like to do the something like the following (psuedo code):

if datasource.datafieldvalue("PrimaryUse") is in dropdownlist.Items then Valid
else set dropdownlist.Selectedvalue = "Default"

Best Answer

You want to check for valid values in the datasource's onDataBinding event handler. The result of a successful datasource data binding is a List cast from the EventArgs. If you know a little LINQ you can write some thing like:

var validData = ((PrimaryUseTable)e.Results).PrimaryUse.Intersect(DropDownList.Items.AsEnumerable())
if(validData.Any())
{
  //Do Stuff
}
else
// Alternate Stuff