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

时间:2010-10-09 09:19:42

标签: c# winforms listbox

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

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);

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

3 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:3)

通常,您不希望在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);

答案 2 :(得分:-3)

以下是一个可以同时添加多个项目的解决方案。

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);
    }
}

希望这可以提供帮助。

相关问题