将多个项目添加到同一行的列表框中

嘿伙计们,我想出了如何一次一行地将项目添加到列表框中:

try { if (nameTxtbox.Text == "") throw new Exception(); listBox1.Items.Add(nameTxtbox.Text); nameTxtbox.Text = ""; textBox1.Text = ""; nameTxtbox.Focus(); } catch(Exception err) { MessageBox.Show(err.Message, "Enter something into the txtbox", MessageBoxButtons.OK, MessageBoxIcon.Error); } 

但我不能在同一行添加多个项目。 喜欢有first_name | last_name | DoB都在同一条线上。 当我做

 listBox1.Items.Add(last_name.Text); 

它将姓氏添加到列表框中的新行,我需要将其添加到与第一个名称相同的行。

听起来你仍然想要添加一个“项目”,但是你希望它包含多个文本。 只需做一些字符串连接(或使用string.Format ),例如。

 listBox1.Items.Add(string.Format("{0} | {1}", first_name.Text, last_name.Text)); 

通常,您不希望在ListBox包含多个列,因为ListBox只有一列。

我认为你正在寻找的是一个ListView,它允许有多个列。 在ListView中,首先创建所需的列

 ListView myList = new ListView(); ListView.View = View.Details; // This enables the typical column view! // Now create the columns myList.Columns.Add("First Name", -2, HorizontalAlignment.Left); myList.Columns.Add("Last Name", -2, HorizontalAlignment.Left); myList.Columns.Add("Date of Birth", -2, HorizontalAlignment.Right); // Now create the Items ListViewItem item = new ListViewItem(first_name.Text); item.SubItems.Add(last_name.Text); item.SubItems.Add(dob.Text); myList.Items.Add(item); 

这里有一个解决方案,可以同时添加多个项目。

 public enum itemsEnum {item1, item2, itemX} public void funcTest2(Object sender, EventArgs ea){ Type tp = typeof(itemsEnum); String[] arrItemEnum = Enum.GetNames(tp); foreach (String item in arrItemEnum){ ListBox1.Items.Add(item); } } 

希望这可以提供帮助。