【问题标题】:ASP.NET OnDataBinding event for EditItemTemplate DropDownListEditItemTemplate DropDownList 的 ASP.NET OnDataBinding 事件
【发布时间】:2011-01-22 12:59:28
【问题描述】:

我在 edititemtemplate 中有一个下拉列表控件,用于定义如下的详细信息视图:

<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>

我有一个数据源定义为对我的数据库的查询,其中有一个名为“PrimaryUse”的列。有时,PrimaryUse 列中可能有一个值未列为下拉列表项之一,因此我的应用程序在尝试将下拉列表的 selectedvalue 绑定到该字段时崩溃。我正在尝试在 edititemtemplate 的 OnDataBinding 事件中创建代码,该代码将检查从数据源返回的值是否是作为下拉列表选项中的项目列出的有效值。我的问题是我不确定如何在后面的代码中获取该列的数据源字段值。这可能吗?是这样吗,有人可以给我一个例子或指出如何做到这一点的方向吗?

所以,在上面列出的 edititemtemplate 的 OnDataBinding 事件中,我想做如下的事情(伪代码):

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

【问题讨论】:

  • 你使用什么语言?
  • vb.net 是我的猜测,因为他有 (if,then,else) 继续,但又是它的伪代码

标签: asp.net data-binding events datasource detailsview


【解决方案1】:

您想检查数据源的 onDataBinding 事件处理程序中的有效值。成功的数据源数据绑定的结果是来自 EventArgs 的 List 强制转换。如果你懂一点 LINQ,你可以写一些类似的东西:

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

【讨论】:

  • 你可能会清理上面的代码,首先将 ((PrimaryUseTable)e.Results) 分配给一个变量,然后在你的 LINQ 查询中使用该变量。我在 Intersect 函数之前添加了 PrimaryUse 列。
【解决方案2】:

您应该能够在代码隐藏中使用 Eval() 来获取此值。但是,一个问题是我认为您尝试在错误的地方执行此操作...您需要在数据控件的 OnDataBinding(或 OnItemDataBound 等)中执行此操作,而不是 DropDownList。 DropDownList 事件将没有正确的上下文,这可能是您遇到问题的原因。

【讨论】:

  • 我使用 C# 作为我的语言。所以你是说我可以在后面的代码中使用 Eval() ?您能否提供一个示例,说明您如何在后面的代码中编写该语句?我只熟悉在 .aspx 页面中使用 eval(): 另外,您是说我需要在 OnDataBinding 中为我的数据源处理这个问题?例如:
  • 我的意思是你需要在 DataBinding 事件中处理任何持有 的控件,因为你感兴趣的实际数据来自哪里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-21
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多