Hey guys, i figured out how to add items to a listbox one line at a time:
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);
}
But I wont to be able to add multiple items to the same line. Like have first_name |
last_name | DoB all on the same line. When I do
listBox1.Items.Add(last_name.Text);
It adds the last name to a new line on the listbox, I need to add it to the same line as the first name.
It sounds like you still want to add one "item", but you want it to contain more than one piece of text. Simply do some string concatenation (or using string.Format
), eg.
listBox1.Items.Add(string.Format("{0} | {1}", first_name.Text, last_name.Text));
Usually you don't want to include multiple columns into a ListBox
, because ListBox is meant to have only one column.
I think what you're looking for is a ListView, which allows to have multiple columns. In a ListView you first create the columns you need
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);
Here has a solution to add multiples items at the same time.
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);
}
}
Hope this can help.