简体   繁体   中英

how to go next line in ListBox?

hey guys i wanna to load a File path in my listBox. everything is ok i just have a problem that is when i Close the app and then open it again loaded files are in the one lane and it recognize them as one item in listBox i tried to use "\\n" , "\\r" none of these works... so what u guys suggest? (i save user changes in App Setting to read them later)

private void Form1_Load(object sender, EventArgs e)
{

    if (Properties.Settings.Default.FileList != string.Empty)
    {
        fileListBox.Items.Add(Properties.Settings.Default.FileList);
    }
    UnlockForm f2 = new UnlockForm();

    if (Properties.Settings.Default.PasswordCheck == true)
        f2.ShowDialog();
    else
        return;
}

private void button1_Click_1(object sender, EventArgs e)
{
    op = new OpenFileDialog();
    op.Title = "Select your stuff";
    op.Filter = "All files (*.*)|*.*";

    if (op.ShowDialog() == DialogResult.OK)
    {
        fileName = op.FileName;
        fileListBox.Items.Add(fileName);
    }

    Properties.Settings.Default.FileList += fileName+"\n";
    Properties.Settings.Default.Save();
}

When creating the property in settings designer:

  • Set the name to whatever you want, for example Files
  • Set the type as System.Collections.Specialized.StringCollection
  • Set the scope as User
  • If you want to have some default values, use ... in Value cell to edit default value.

Then you can easily set it as DataSource of the ListBox .

listBox1.DataSource = Properties.Settings.Default.Files;

Also to add some values:

Properties.Settings.Default.Files.Add("something");
Properties.Settings.Default.Save();

If you added something to the Files , if you want the ListBox shows the changes, set DataSource to null and then to Files again.

It looks like you have defined your FileList as String in our App Settings. There are two ways you can approach this.

a) Using FileList as Collection.

You can change the Type of FileList to StringCollection in your App Settings. Then, you can add items to your list as follows

 fileListBox.Items.AddRange(Properties.Settings.Default.FileList.Cast<string>().ToArray());

b) Using FileList as String.

If you really want to retain Properties.Settings.Default.FileList as string, you would need to split it on the run using your delimiter character (let's say ';')

fileListBox.Items.AddRange(Properties.Settings.Default.FileList.Split(new[] { ';' },StringSplitOptions.RemoveEmptyEntries));

In your case, a collection might be a better approach unless you have specific reasons outside the scope of OP to use string.

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