[英]How do i get a list of object in a Listbox?
I was trying to create a personal list using WinForms.我正在尝试使用 WinForms 创建个人列表。 I try to create a new entry via button click.
我尝试通过单击按钮创建一个新条目。 I have a list of objects with string properties
Name
and Number
.我有一个具有字符串属性
Name
和Number
的对象列表。
How can I show the list of objects in my ListBox?如何在我的 ListBox 中显示对象列表?
namespace sometestname
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Personallistshow(object sender, EventArgs e)
{
}
public void NewItemButton_Click(object sender, EventArgs e)
{
Personallist.Add(new Entrys() { Name = NameBox.Text, Number = Numbox.Text });
}
public List<Entrys> Personallist= new List<Entrys>();
}
public partial class Entrys
{
public string Name { get; set; }
public string Number { get; set; }
}
}
The user has 2 Textboxfields.用户有 2 个文本框字段。 If they click the
NewItemButton
, than create a new Entrys
object.如果他们单击
NewItemButton
,则创建一个新条目Entrys
。 This new Entrys
object should be added to Personallist
object and ListBox should show the updated list.这个新的条目
Entrys
应该添加到Personallist
列表 object 并且列表框应该显示更新的列表。
List<Entrys> someList = ...;
Personallist.DataSource = someList;
You should use a bindinglist and set the datasourcebinding after initializing your form.您应该在初始化表单后使用绑定列表并设置数据源绑定。
Something like:就像是:
public partial class Form1 : Form
{
public BindingList<Entrys> Personallist = new BindingList<Entrys>();
public Form1()
{
InitializeComponent();
comboBox1.DataSource = Personallist;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Number";
}
private void button1_Click(object sender, EventArgs e)
{
Personallist.Add(new Entrys() { Name = "TESTNAME", Number = "TESTNR" });
}
}
public partial class Entrys
{
public string Name { get; set; }
public string Number { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.