DropDownList how to set DataSource
Hi I have a DropDownList.
I need visualize in it a SINGLE value (ListItem) the current Logged in User, like
<asp:ListItem>Joe</asp:ListItem>
Here my wrong code, if the UserName is "Joe", the DropDownList visualize for every single letter an ListItem: Examp开发者_运维技巧le:
<asp:ListItem>J</asp:ListItem>
<asp:ListItem>o</asp:ListItem>
<asp:ListItem>e</asp:ListItem>
This is my code:
<asp:DropDownList ID="uxUserListSelector" runat="server"></asp:DropDownList>
MembershipUser myCurrentUser = Membership.GetUser();
myUserList.DataSource = myCurrentUser.UserName;
myUserList.DataBind();
Any idea how to fix it? Thanks
You're setting the DataSource
to a string (myCurrentUser.UserName
), so it's interpreting that as an array of characters and binding to it accordingly.
As for how to fix it, what exactly are you trying to do? Why are you using a DropDownList
to display a single item? Why not a TextBox
or a Label
?
For now, I'm assuming that you want the DropDownList
to contain all of the users, and to pre-select the current user. Is this correct? If so, then you'll need a method to get the names of all of the users and bind the DropDownList
to that list of names. (A simple IList<string>
of user names will probably do, but if you want more control over the DataTextItem
and DataValueItem
then an IList<>
of a custom object may be better.)
Once it's bound to the list of usernames, you can set the selected value to the current username.
Edit: Based on your response, the overall code would look something like this:
// 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;
You will, of course, want to wrap some of this in proper error handling. For example, the last line will throw an exception if the supplied username is not found in the list.
精彩评论