您好,我有一个 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
显示单个项目?为什么不是 TextBox
或 Label
?
现在,我假设您想要 DropDownList
包含所有用户,并预选当前用户。它是否正确?如果是这样,那么您将需要一种方法来获取所有用户的名称并绑定(bind) DropDownList
到那个名单。 (一个简单的 IList<string>
用户名可能就可以了,但如果你想更多地控制 DataTextItem
和 DataValueItem
那么自定义对象的 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/