Gib*_*boK 1 c# asp.net drop-down-menu
嗨,我有一个DropDownList.
我需要在其中可视化一个SINGLE值(ListItem)当前登录用户,就像
<asp:ListItem>Joe</asp:ListItem>
Run Code Online (Sandbox Code Playgroud)
这是我的错误代码,如果UserName是"Joe",DropDownList可以为ListItem的每个字母显示:示例:
<asp:ListItem>J</asp:ListItem>
<asp:ListItem>o</asp:ListItem>
<asp:ListItem>e</asp:ListItem>
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
<asp:DropDownList ID="uxUserListSelector" runat="server"></asp:DropDownList>
MembershipUser myCurrentUser = Membership.GetUser();
myUserList.DataSource = myCurrentUser.UserName;
myUserList.DataBind();
Run Code Online (Sandbox Code Playgroud)
知道怎么解决吗?谢谢
你正在设置DataSource一个字符串(myCurrentUser.UserName),所以它将它解释为一个字符数组并相应地绑定它.
至于如何解决它,你究竟想做什么?你为什么用a DropDownList来显示单个项目?为什么不是a TextBox或a Label?
现在,我假设您希望DropDownList包含所有用户,并预先选择当前用户.它是否正确?如果是这样,那么您将需要一种方法来获取所有用户的名称并将其绑定DropDownList到该名称列表.(一个简单IList<string>的用户名可能会这样做,但是如果你想要更多控制DataTextItem,DataValueItem那么IList<>一个自定义对象可能会更好.)
一旦绑定到用户名列表,就可以将所选值设置为当前用户名.
编辑:根据您的回复,整体代码看起来像这样:
// 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;
Run Code Online (Sandbox Code Playgroud)
当然,您将希望将其中的一部分包装在正确的错误处理中.例如,如果在列表中找不到提供的用户名,则最后一行将引发异常.
| 归档时间: |
|
| 查看次数: |
8082 次 |
| 最近记录: |