[英]C#: public new string ToString() VS public override string ToString()
[英]Public override string toString, ArrayList and Listbox output in multiplelines?
我整夜都在为这个C#问题苦苦挣扎。
我有一个重写ToString(),它工作正常,我可以将数据放入ListBox中。 但是由于数据非常长,并且带有许多类,因此输出变长。 我希望能够将ListBox输出分成多行。
这是类文件中的替代:
//ToString
public override string ToString()
{
return "Name " + firstName + lastName + ". Nationality " + nationality + ". Lives in " + address + " " + zipCode + " " + city + " " + country + "."//
+ " Height is " + height + " meters. Hair color is " + hairColor + " and eye color is " + eyeColor + ". Specialmarkings: "//
+ specialMark + ". Is associated with " + association + ". Codename is " + codeName + "Photo (filename): " + photo;
}
这是索引代码:
public partial class Index : System.Web.UI.Page
{
static ArrayList personarraylist;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
personarraylist = new ArrayList();
}
}
protected void ButtonCreate_Click(object sender, EventArgs e)
{
//create new object
Person p = new Person(TextBox1FirstName.Text, TextBox2LastName.Text, TextBox3Nation.Text, TextBox4Address.Text, //
TextBox5City.Text, TextBox7Country.Text, //
TextBox10HairColor.Text, TextBox11EyeColor.Text, TextBox12SpecialMark.Text, TextBox13Asso.Text, TextBox14Codename.Text, TextBox15Photo.Text, //
Convert.ToDouble(TextBox9Height.Text), Convert.ToInt32(TextBox6ZipCode.Text), Convert.ToInt32(TextBox8Pass.Text));
//add object to arraylist
personarraylist.Add(p);
}
protected void ButtonShow_Click(object sender, EventArgs e)
{
//clear list box
ListBox1.Items.Clear();
//loop through Arraylist
for (int i = 0; i < personarraylist.Count; i++)
{
ListBox1.Items.Add(personarraylist[i].ToString());
ListBox1.Items.Add("");
TextBox1.Text = "";
}
}
}
是否可以在ListBox中以多行中断输出? 我试图在重写返回中插入一些html中断标签,但是这些标签被剥离了,是的,这是一个web应用程序。
在此先感谢您的时间。 PS我是C#(学生)的新手,所以要友善;)
更新:再次感谢您的帮助,我已经尝试使用Environment.Newline和其他解决方案,但是当在ListBox中显示文本时,这些方法似乎被忽略了。 我可以在后面的代码中看到断点,但是在浏览器中,列表框仍然只将它们全部放在一行中。 因此,我决定改用TextBox,它会自动断开文本以及指向的位置。
//loop through Arraylist
for (int i = 0; i < personarraylist.Count; i++)
{
TextBox1.Text += personarraylist[i].ToString();
}
再次感谢您的帮助:-)
您可以使用Environment.NewLine
或简单地使用"\\n"
来创建多行文本。
如果这不起作用,则可以尝试使用DataList
控件:
<asp:DataList id="myDataList" runat="server">
<ItemTemplate>
Line 1
<br />
Line 2
</ItemTemplate>
</asp:DataList>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.