0

I'm trying to add rows from a class to a datagridview which is in my main_form. To access, I'm using the method posted by vr_driver here

TextBox t = Application.OpenForms["Form1"].Controls["textBox1"] as TextBox;

It works for a datagridview on my brand new project, but in the old project which contains more elements it doesn't. It always comes with : System.NullReferenceException as also did to Deniz on the comment.

DataGridView t = Application.OpenForms["form_main"].Controls["gridSchedule"] as DataGridView;

row = t.Rows.Count = System.NullReferenceException

What could be possible wrong? I already set the modifier for Public.

Thank you.

fdroid
  • 13
  • 1
  • 6
  • Is the grid contained in another control? That code will get only the controls that are directly hosted on the form container, not if they are in other containers (groupbox, panel) – Steve Jun 09 '20 at 20:07
  • Yes, it's contained in a Panel inside a groupbox. That's explain everything! Is there a way to access anyway? – fdroid Jun 10 '20 at 00:41
  • Instead of using this direct access to an internal element of a form, why not giving the _main_form_ a method that executes the work on its onw datagridview? In this way the only element that you need from the OpenForms collection is the form itself, then once you have the instance you could call a public method that executes the work. Externally none should be able to access the controls element of the form – Steve Jun 10 '20 at 07:17
  • Thanks Steve! The problem is that I can't access the method on the class. I did as mentioned: On the form_main `public void CreateRow() { gridSchedule.Rows.Add("Test");}` On the Class: `Form mF = Application.OpenForms["main_form"];` then in the method inside the class: mF.(cannot find the CreateRow method). Also if I instantiate the main_form when I run the CreateRow() it doesn't add the rows into the main form datagridview – fdroid Jun 10 '20 at 13:04
  • I was able to change the form_main by [reference instead of instantiate](https://stackoverflow.com/questions/17092336/update-control-and-refresh-form-by-call-from-class-to-main-form) `public void AddRow(main_form Sender) { Sender.CreateRow();} ` and on form_main `ManageFiles mF = new ManageFiles(); mF.AddRow(this); ` But did not figure out how to do it using OpenFormCollection. – fdroid Jun 10 '20 at 13:18
  • Should be _main_form mF = Application.OpenForms["main_form"] as main_form;_ (Or whatever type is the form named _main_form_) then you have the proper instance to call _mF.CreateRow();_ – Steve Jun 10 '20 at 13:29
  • Thank you @Steve. This was I was missing. Grazie Mille – fdroid Jun 10 '20 at 13:38
  • All right, thank you. – fdroid Jun 10 '20 at 13:55

0 Answers0