【问题标题】:DropDownList how to set DataSourceDropDownList如何设置DataSource
【发布时间】:2010-12-29 15:34:07
【问题描述】:

您好,我有一个 DropDownList。

我需要在其中可视化当前登录用户的 SINGLE 值 (ListItem),例如

<asp:ListItem>Joe</asp:ListItem>

这是我的错误代码,如果 UserName 是“Joe”,DropDownList 会为每个字母显示一个 ListItem: 示例:

<asp:ListItem>J</asp:ListItem>
<asp:ListItem>o</asp:ListItem>
<asp:ListItem>e</asp:ListItem>

这是我的代码:

<asp:DropDownList ID="uxUserListSelector" runat="server"></asp:DropDownList>

        MembershipUser myCurrentUser = Membership.GetUser();
        myUserList.DataSource = myCurrentUser.UserName;
        myUserList.DataBind();

知道如何解决吗?谢谢

【问题讨论】:

    标签: c# asp.net drop-down-menu


    【解决方案1】:

    您将 DataSource 设置为字符串 (myCurrentUser.UserName),因此它将其解释为字符数组并相应地绑定到它。

    至于如何解决它,您到底想做什么?为什么要使用DropDownList 来显示单个项目?为什么不是TextBoxLabel

    现在,我假设您希望 DropDownList 包含 所有 用户,并预先选择当前用户。这个对吗?如果是这样,那么您将需要一种方法来获取所有用户的名称并将DropDownList 绑定到该名称列表。 (一个简单的用户名IList&lt;string&gt; 可能就可以了,但是如果您想对DataTextItemDataValueItem 进行更多控制,那么自定义对象的IList&lt;&gt; 可能会更好。)

    一旦绑定到用户名的列表,您可以将选定的值设置为当前用户名。

    编辑:根据您的回复,整体代码如下所示:

    // You'll need a method to get all of the users, this one is just for illustration
    myUserList.DataSource = userRepository.GetAllUsers();
    // Set this to the property on the user object which contains the username, to display in the dropdownlist
    myUserList.DataTextField = "Username";
    // Set this to the property on the user object which contains the user's unique ID, to be the value of the dropdownlist (this might also be the username)
    myUserList.DataValueField = "UserID";
    myUserList.DataBind();
    // There are a number of different ways to pre-select a value, this is one
    myUserList.Items.FindByText(myCurrentUser.UserName).Selected = true;
    

    当然,您会希望在适当的错误处理中包含其中的一些内容。例如,如果在列表中找不到提供的用户名,最后一行将引发异常。

    【讨论】:

    • 您好,感谢您的想法,我需要“预选当前用户”下拉列表。你能发布一个简单的代码示例吗?我是初学者:-) thnaks
    • 非常感谢您的帮助,现在正在工作,再次感谢 :-)
    猜你喜欢
    • 2011-04-27
    • 2011-07-20
    • 1970-01-01
    • 2011-03-13
    • 2013-12-19
    • 2018-01-09
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多