c# - How can I save a listbox in a text file -


i have 2 forms, on form1 have button , in form2 have listbox data. want click button on form1 , save data form2 listbox in text file.

what have tried:

this button on form1

private void toolstripbuttonguardar_click(object sender, eventargs e)     {         var myform = new formver();          //escolher onde salvar o arquivo         savefiledialog sfd = new savefiledialog();         sfd.initialdirectory = environment.getfolderpath(environment.specialfolder.desktop);         sfd.title = "guardar";         sfd.filter = "arquivos txt (*.txt)|*.txt";          if (sfd.showdialog() == dialogresult.ok)         {             try             {                  file.writealllines(sfd.filename, myform.listbox.items.oftype<string>());                  //mensagem de confirmação                 messagebox.show("guardado com sucesso", "notificação", messageboxbuttons.ok, messageboxicon.information);             }             catch (exception ex)             {                 messagebox.show(ex.message, "erro", messageboxbuttons.ok, messageboxicon.error);             }         }     } 

but doesn't work, save file blank.

myform.listbox.items.oftype<string>() 

is going return empty enumerable since items contains listboxitem instances

the following should work:

listbox listbox = myform.listbox; ienumerable<string> lines = listbox.items.select(item => listbox.getitemtext(item));  file.writealllines(sfd.filename, lines); 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -