使用列表框并向其中添加对象。c#将对象添加到列表框并显示其中的对象字符串
该对象包含2个变量,可以说用户名和userid。
如何添加列表中的对象,如 listbox.Items.add(object); 并显示该对象的用户名?
thnx!
使用列表框并向其中添加对象。c#将对象添加到列表框并显示其中的对象字符串
该对象包含2个变量,可以说用户名和userid。
如何添加列表中的对象,如 listbox.Items.add(object); 并显示该对象的用户名?
thnx!
设置DataTextField
和DataValueField
ListBox a = new ListBox();
a.DataTextField = "username";
a.DataValueField = "userid";
要使用.Add
方法添加你可以使用:
a.Items.Add(new ListItem() { Value = User.ID, Text = User.Name });
你可以用你的ListBox的DisplayMember属性。
listbox.DisplayMember = "username";
还有一个等价的属性来定义实际值,您可以用它来检索用户标识。例如,如果你定义列表如下:
MyObject newItem = (MyObject) listbox.SelectedItem; // Gets the selected MyType
// OR
string username = listbox.Text; // Gets the selected user name using the DisplayMember property of the listbox
// OR
string userid = listbox.SelectedValue; // Gets the selected user's userid using the ValueMember property of the listbox
你还可以:
listbox.DisplayMember = "username";
listbox.ValueMember = "userid";
var item1 = new MyType { username = "user1", userid = "id1" }; // Create an item for the list
listbox.Items.Add(item1); // Add the item
listbox.SelectedIndex = 0; // Selects the first item
然后你就可以通过3点不同的方式(项目,值或文本)这样的引用在列表中的对象设置所选项目相同三种方式:
listbox.SelectedItem = item1;
// OR
listbox.Text = item1.username;
// OR
listbox.SelectedValue = item1.userid;
您可以使用DisplayMember和ValueMember属性来显示的UserName
财产你的对象,并使用其UserId
属性作为列表项的值:
class YourItem
{
public string UserName { get; set; }
public string UserId { get; set; }
}
yourListBox.DisplayMember = "UserName";
yourListBox.ValueMember = "UserId";
yourListBox.Items.Add(new YourItem {
UserName = "FooName",
UserId = "FooId"
});
您可以覆盖“的ToString”方法。
class User
{
public string username { set; get; }
public string userid { set; get; }
public override string ToString()
{
return username;
}
}