简体   繁体   中英

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

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

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

对于WinForms:

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

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

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

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

A couple seconds worth of googling

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM