在列表框中显示消息框中的多个信息
问题描述:
我正在研究一个程序,该程序让我输入有关船的信息并将该信息添加到列表框中。唯一会出现在列表框中的是船的名字。我需要知道如何显示其他文本框中的所有信息,例如长度,风帆大小和引擎在消息框中。任何帮助表示赞赏。在列表框中显示消息框中的多个信息
public partial class Form1 : Form
{
ArrayList Home;
public Form1()
{
InitializeComponent();
Home = new ArrayList();
}
private void btnAddApartment_Click(object sender, EventArgs e)
{
//instantiate appartment and add it to arraylist
try
{
Apartment anApartment = new Apartment(txtID.Text, txtAddress.Text, int.Parse(txtYearBuilt.Text), int.Parse(txtBedrooms.Text),
double.Parse(txtSquareFootage.Text), double.Parse(txtPrice.Text), txtFurnished.Text);
Home.Add(anApartment);
ClearText(this);
}
catch (Exception)
{
MessageBox.Show("Make sure you entered everything correctly!", "Error", MessageBoxButtons.OK);
}
}
private void btnAddHouse_Click(object sender, EventArgs e)
{
try
{
House aHouse=new House(txtID.Text, txtAddress.Text, int.Parse(txtYearBuilt.Text), int.Parse(txtBedrooms.Text),
double.Parse(txtSquareFootage.Text), double.Parse(txtPrice.Text),int.Parse(txtGarageCapacity.Text));
Home.Add(aHouse);
AddHouseToListBox();
ClearText(this);
}
catch (Exception)
{
MessageBox.Show("Make sure you entered everything correctly!", "Error", MessageBoxButtons.OK);
}
}
private void ClearText(Control controls)
{
foreach (Control control in controls.Controls)
{
if (control is TextBox)
{
((TextBox)control).Clear();
}
}
}
private void AddHouseToListBox()
{
lstHouse.Items.Clear();
foreach (House person in Home)
{
lstHouse.Items.Add(person.GetAddress());
}
}
private void AddApartmentToListBox()
{
lstApartment.Items.Clear();
foreach (Apartment persons in Home)
{
lstApartment.Items.Add(persons.GetAddress());
}
}
答
如果您要表示要在列表框中显示多列数据,则应考虑切换到ListView。
一个的ListView控件添加到您的窗体:
你会然后使用类似下面的代码添加其他列的值。
一个我假设你有一个名为txtBoatName,txtLength,txtSailSize 4个文本框,txtEngines
// You can either set the columns and view in code like below, or use
// the Form designer in Visual Studio to set them. If you set them in code,
// place the following in Form.Load
listView1.View = View.Details;
listView1.Columns.Add("Boat Name", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Length", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Sail Size", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Engines", -2, HorizontalAlignment.Center);
// When you want to add a boat to the ListView, use code like the following:
ListViewItem item1 = new ListViewItem(txtBoatName.Text,0);
item1.SubItems.Add(txtLength.Text);
item1.SubItems.Add(txtSailSize.Text);
item1.SubItems.Add(txtEngines.Text);
listView1.Items.Add(item1);
你能告诉我们你目前拥有的代码。这听起来像你需要充分填充ListBoxItem,但需要确保代码 – 2012-04-17 17:01:39
我只是把代码放在 – 2012-04-17 23:52:28
哇,代码是完全不同的问题是什么(家园和公寓与船和风帆尺寸) 。无论如何,为了更直接地回答这个问题,“Apartment.GetAddress()”的代码是什么?如果你真的想将整个地址转储到列表框的一列(与ListView中的多列相似,就像在我的答案中一样),那么问题出在你的字符串格式为Apartment.GetAddress()。很可能你包括CR,LF或两者。 – GalacticJello 2012-04-18 15:34:14