C#如何在组合框中添加数据 [英] C# how to add datas in combobox
问题描述
我有老师班,而控制班班有老师班的名单`
i have Teacher class, and Controller class which has List from Teacher class`
static public List<Teacher> teachers = new List<Teacher>();
i有插入表单,我应该写新教师数据并将其添加到另一个名称为的另一种形式的combobox.Combobox中Add_New_Group。如何添加我在Insert表单中编写的新教师数据和另一个`add_New_Group表单中的combobox。
我尝试了什么:
在组合框中,它会显示教师的姓名和姓氏,但是当我添加新教师并保存时,在组合框中显示我(收藏)不是名字和姓氏。我的错是什么?
i have Insert Form, where i should write new teachers datas and add it in combobox.Combobox located in another form which name is Add_New_Group.How can i add new teacher's data which i have written in Insert form and combobox located in another`Add_New_Group form.
What I have tried:
In combobox it will show me teacher's name and surname,but when i add new teacher and save it, in combobox shows me (Collections) not name and surname.What's my mistake?
public partial class Insert : Form // in Insert form
{
private void button2_Click(object sender, EventArgs e)
{
Teacher x = new Teacher(textBox1.Text,textBox2.Text, int.Parse(textBox3.Text),
textBox4.Text, n);
Controller.teachers.Add(x);
}
}
public partial class Add_New_Group : Form // in Add_New_Group form
{
public Add_New_Group()
{
InitializeComponent();
comboBox1.Items.Add(Controller.teachers);
}
}
推荐答案
一种简单的方法是将属性和类放置为public static
在Program.cs
文件中。然后从你的表单中引用它们很简单,但似乎你已经在你的Controller类中做了这个。
所以也许你应该刷新组合框的内容
使用.Refresh
或.Invalidate
另见这里的答案:如何将组合框项目从一种形式添加到另一种形式组合框 [ ^ ]
A simple way to do this is to place your properties and classes aspublic static
in yourProgram.cs
file. Then it is simple to refer to them from your Forms, but it seems you already did this in your Controller class.
So maybe you should refresh the contents of yourcomboBox
by using.Refresh
or.Invalidate
Also see answers here: How to add combobox item from one form to another form combobox[^]
将项目添加到组合框更容易的一种方法是覆盖集合项的ToString()
方法,以便它返回所需的属性。
One way to make adding items to a Combo box easier is to override theToString()
method of the collection item, so that it returns the desired property.
public class MyItem
{
public string Name { get; set; }
public override string ToString()
{
return this.Name;
}
}
要向组合框中添加项目:
To add items to your combobox:
// assuming a list of MyItem objects
List<MyItem> myItems;
// you can do something like this
this.comboBox.Items.Add(myItems);
简而言之:如何:将Windows窗体ComboBox或ListBox控件绑定到数据| Microsoft Docs [ ^ ]
这篇关于C#如何在组合框中添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!