[英]How do i get a list of object in a Listbox?
我正在嘗試使用 WinForms 創建個人列表。 我嘗試通過單擊按鈕創建一個新條目。 我有一個具有字符串屬性Name
和Number
的對象列表。
如何在我的 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; }
}
}
用戶有 2 個文本框字段。 如果他們單擊NewItemButton
,則創建一個新條目Entrys
。 這個新的條目Entrys
應該添加到Personallist
列表 object 並且列表框應該顯示更新的列表。
List<Entrys> someList = ...;
Personallist.DataSource = someList;
您應該在初始化表單后使用綁定列表並設置數據源綁定。
就像是:
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.