c# - DropDownList如何设置DataSource

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

您好,我有一个 DropDownList。

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

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

这是我的错误代码,如果用户名是“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();

知道如何解决吗?谢谢

最佳答案

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

至于如何修复它,你到底想做什么?为什么要使用 DropDownList显示单个项目?为什么不是 TextBoxLabel

现在,我假设您想要 DropDownList包含所有用户,并预选当前用户。它是否正确?如果是这样,那么您将需要一种方法来获取所有用户的名称并绑定(bind) DropDownList到那个名单。 (一个简单的 IList<string> 用户名可能就可以了,但如果你想更多地控制 DataTextItemDataValueItem 那么自定义对象的 IList<> 可能会更好。)

一旦绑定(bind)到用户名列表,您就可以将所选值设置为当前用户名。

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

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

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

关于c# - DropDownList如何设置DataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4555407/

相关文章:

java - 如何说一个 DropDownChoice 来更新它的选择列表?

javascript - 使用 vanilla JavaScript 操作 CSS 类

c# - JavaScript 未定义属性

带有 actionLayout 的 Android 操作栏菜单项无法正常工作

c# - 播放 .flv 文件时找不到视频或访问被拒绝

c# - 服务器超时后,c# 中的电子邮件发送服务无法恢复

ASP.NET MVC : How should it work with subversion?

c# - OWIN 中 OAuthAuthorizationServer 的自定义响应

c# - 使用SoundEffectInstance作为背景音乐可以接受吗?

c# - OCS/Lync 网站存在指示