在asp.net中填充列表框控件

3

我有一个代码块,返回一个员工对象列表。
结果集包含多个员工记录。其中一个元素是EmployeeID。
我需要用只有EmployeeID的方式填充listview(lstDepartment)。我该怎么做?

lstDepartment.DataSource = oCorp.GetEmployeeList(emp);
lstDepartment.DataBind()
3个回答

3

您还需要指定以下内容:

     lstDepartment.DataSource = oCorp.GetEmployeeList(emp);
     lstDepartment.DataTextField = "EmployeeID";
     lstDepartment.DataValueField = "EmployeeID";
     lstDepartment.DataBind()

ListView和ListBox并不相同,它既没有DataTextField属性,也没有DataValueField属性。 - Tim Schmelter
我的错 @TimSchmelter... 我的控件是一个ListBox,不是一个Listview。 - DNR

1
一种方法是使用匿名类型:
lstDepartment.DataSource = oCorp.GetEmployeeList(emp)
                                .Select(emp => new { emp.EmployeeID });
lstDepartment.DataBind();

编辑:但你也可以选择所有列,只显示其中一列。ListView不是ListBoxDropDownList。只有你使用的内容才会被显示。所以如果你的ItemTemplate看起来像:

<ItemTemplate>
  <tr runat="server">
    <td>
      <asp:Label ID="LblEmployeeID" runat="server" Text='<%# Eval("EmployeeID") %>' />
    </td>
  </tr>

无论您的DataSource中有什么内容,只有EmployeeID会被显示。


1

您可以在 ListView 的 ItemTemplate 中指定要显示的内容。

<asp:ListView ID="lstDepartment" runat="server">
   <ItemTemplate>
     <p>  <%#Eval("EmployeeID") %> </p>
   </ItemTemplate>
</asp:ListView>

@TimSchmelter:啊!我应该仔细阅读!感谢友好地指出:)删除答案,因为现在不值得了! - Shyju

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接