LFLJM
LFLJM

Reputation: 85

listing file names using ofd on DGV can't be done because of the data source

I am a beginner in programming in general. My app has a button listing names of selected files on DGV. I added a row for file names on windows Forms Designer using DGV Tasks. The code is as follows:

      {
          OpenFileDialog ofd = new OpenFileDialog();
          ofd.Filter = "Word(*.docx)| *.docx|PPT(*.pptx)|*.pptx|PDF(*.pdf)|*.pdf|Alle Dateien(*.*)|*.*";
          ofd.Multiselect = true;

          
             if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
              {
                  string[] dateinamen = ofd.SafeFileNames;
                  for (int i = 0; i < ofd.FileNames.Count() - 1; i++)
                  {
                      dataGridView1.Rows.Add(dateinamen[i]);
                  }

              }
      } 

After creating this button, I made a class to use as data source of this DGV(on windows Forms Design -> DGV tasks -> Choose data source -> Object -> Class I created) Then, I tried to open files to list their names using the button I mentioned above. And I get the following message: "Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound"

I can kinda understand why, and I want to fix this. Best option would be, I guess, to put ofd codes to Datasource class, but I have no idea how. I'm not even sure if it'd be right. If not, it'll be great if I get the right way to fix this problem.

Thanks in advance!

Upvotes: 0

Views: 46

Answers (1)

LFLJM
LFLJM

Reputation: 85

 BindingList<Datei> dateienList = new BindingList<Datei>();

  private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog(); 
            ofd.Filter = "Word(*.docx)| *.docx|PPT(*.pptx)|*.pptx|PDF(*.pdf)|*.pdf|Alle Dateien(*.*)|*.*";
            ofd.Multiselect = true;
            try
            {
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foreach (String path in ofd.FileNames) 
                    {                                      
                        Datei datei = new Datei();  
                        datei.filePath = path; 
                        datei.Dateiname = Path.GetFileName(path);
                     dateienList.Add(datei);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler! Die Datei kann nicht gelesen werden: " + ex.Message);
            }
        }

public class Datei //class as Datasource
 {                     // 
        [DisplayName("Dateiname")] 
        public string Dateiname { get; set; }
       
        public string filePath { get; set; }
      
      
     
    }
}

Upvotes: 0

Related Questions