开发者

ASP.NET OnDataBinding event for EditItemTemplate DropDownList

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 selectedv开发者_如何学编程alue 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"


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 


You should be able to just use Eval() in the codebehind to get this value. One problem though, is that I think you are trying to do this in the wrong place... You need to do this in the OnDataBinding (or OnItemDataBound, etc) for the data control, not the DropDownList. The DropDownList event will not have the correct context, which may be why you are having a problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜