[英]C# add items to list from class then add list items to listbox
I'm a student in a C# class and this is my introductory assignment to Classes, so please bear with me. 我是C#班的学生,这是我对班级的介绍性作业,所以请多多包涵。 When the New button is pressed, a CPerson object will be created using the name and phone values and the object will be added to a List<>.
按下“新建”按钮时,将使用名称和电话值创建CPerson对象,并将该对象添加到List <>。
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
}
public partial class Form1 : Form
{
private List<CPerson> PhoneNum = new List<CPerson>(); //<CPerson> or <string>?
public Form1()
{
InitializeComponent();
newbutton.Enabled = false;
changebutton.Enabled = false;
savebutton.Enabled = false;
}
private void newbutton_Click(object sender, EventArgs e)
{
changebutton.Enabled = true;
savebutton.Enabled = true;
PhoneNum.Add(new CPerson { Name = Namebox.Text + " : ", Phone = phonebox.Text });
listBox1.Items.Add(PhoneNum); //text = "Collection"
}
The assignment says "The CPerson ToString() override will be used to display the name and phone number in the listbox" as shown in the above image, which I don't necessarily understand, but I'm guessing I have to use something like this? 作业显示“ CPerson ToString()覆盖将用于在列表框中显示名称和电话号码”,如上图所示,我不一定理解,但是我猜我必须使用类似这个?
CPerson data = new CPerson();
data.ToString();
Either way, as the code is now, all I get in my listbox is "(Collection)". 无论哪种方式,就像现在的代码一样,我在列表框中得到的都是“(Collection)”。 Any help would be appreciated!
任何帮助,将不胜感激!
That is asking to override the ToString() method. 那就是要求重写ToString()方法。 You can do it like this:
您可以这样做:
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
public override string ToString()
{
return Name + ": " + Phone;
}
I did not get right the part of adding to the list, but I assume you can do the following using ToString(): 我没有正确地添加到列表中,但是我想您可以使用ToString()执行以下操作:
listBox1.Items.Add(data.ToString());
Close... 关...
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
public override string ToString()
{
return Name + ": " + Phone;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.