Scott G

Scott G

  • NA
  • 103
  • 7k

Weird issues when adding to a winform listbox

Aug 23 2019 11:12 AM
I have an application that allows the user to select a file and display the folder\filename in a listbox. The problem I am having is when it adds it to the listbox it adds a blank row above it. This is causing a second row to be created in the database with this field being blank. This only happens though with the first file selected. If I go back to add another one it does not add the blank row. It also does not happen if I select multiple files at once to add. In addition to that if I minimize then maximize the application any items listed in the listbox are duplicated.
  1. private void btnModSel_Click(object sender, EventArgs e)  
  2. {  
  3. System.IO.Stream myStream;  
  4. OpenFileDialog openFiledialog1 = new OpenFileDialog();  
  5. openFiledialog1.FilterIndex = 2;  
  6. openFiledialog1.InitialDirectory = "P:\\Folder\\subfolder";  
  7. openFiledialog1.RestoreDirectory = true;  
  8. openFiledialog1.Multiselect = true;  
  9. openFiledialog1.Title = "Please Select a File";  
  10. if (openFiledialog1.ShowDialog() == DialogResult.OK)  
  11. {  
  12. foreach (String file in openFiledialog1.FileNames)  
  13. {  
  14. try  
  15. {  
  16. if ((myStream = openFiledialog1.OpenFile()) != null)  
  17. {  
  18. using (myStream)  
  19. {  
  20. lstModFiles.Items.Add(file.Substring(52));  
  21. }  
  22. }  
  23. }  
  24. catch (Exception ex)  
  25. {  
  26. MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);  
  27. }  
  28. }  
  29. }  
  30. }  

Answers (7)