Mathew
Mathew

Reputation: 43

Sending a string to a listbox (C#)

I currently have a string being sent to a TextBox, although instead is it possible to send it to a listbox?

private void buttonLB_Click(object sender, EventArgs e)
{
    string machineName = (@"\\" + System.Environment.MachineName);
    ScheduledTasks st = new ScheduledTasks(machineName);
    // Get an array of all the task names
    string[] taskNames = st.GetTaskNames();
    richTextBox6.Text = string.Join(Environment.NewLine, taskNames);
    st.Dispose();
}

Upvotes: 3

Views: 20661

Answers (6)

iAndr0idOs
iAndr0idOs

Reputation: 257

A couple seconds worth of googling

foreach(String s in taskNames) {
    listBox1.Items.add(s);
}

Upvotes: -2

Jon Raynor
Jon Raynor

Reputation: 3892

Use AddRange, this can take an array of objects.

Here's some sample code:

Start a new WinForms project, drop a listbox on to a form:

 string[] names = new string[3];
 names[0] = "Item 1";
 names[1] = "Item 2";
 names[2] = "Item 3";
 this.listBox1.Items.AddRange(names);

For your specific example:

// Get an array of all the task names       
string[] taskNames = st.GetTaskNames();      
this.listBox1.Items.AddRange(taskNames);

If this is called repeatedly, call clear as needed before adding the items:

this.listBox1.Items.Clear();

Upvotes: 0

Renatas M.
Renatas M.

Reputation: 11820

ListBox has Items property. You can use Add() method to add object to list.

listBox.Items.Add("My new list item");

Upvotes: 1

yas4891
yas4891

Reputation: 4862

For WinForms:

listView.Items.Add(string.Join(Environment.NewLine, taskNames));

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23142

Instead of setting the textbox's Text property, add a ListItem to the listbox's Items collection.

lstBox.Items.Add(new ListItem(string.Join(Environment.NewLine, taskNames));

Or...

foreach(var taskName in taskNames)
    lstBox.Items.Add(new ListItem(taskName));

Upvotes: 2

David Ruttka
David Ruttka

Reputation: 14409

You can add the joined task names as a single item

listbox1.Items.Add(string.Join(Environment.NewLine, taskNames));

Or you can add each of the task names as a separate item

foreach (var taskName in taskNames)
{
    listbox1.Items.Add(taskName);
}

Upvotes: 5

Related Questions