-1

I have 2 forms...and the textbox in the other form

  • how can I get the typed text from the other form ?
  • I tried this but it gives error.
  • List item
var mainForm = Application.OpenForms.OfType<Form1>().Single();
mainForm.URL_BOX.Text();

The Error

Sycho2 2
  • 9
  • 3
  • _I tried this but it gives error._ What error? Please be more precise when asking. Surely, to read the Text property of a TextBox you don't use the parenthesys – Steve Feb 24 '22 at 14:06
  • `.Text()` is not a Winform property/method. – Lei Yang Feb 24 '22 at 14:07
  • "but it gives error." - what error? In which line? – Thomas Weller Feb 24 '22 at 14:07
  • [`TextBox.Text`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.text?view=windowsdesktop-6.0) is a property not a method. – Tim Schmelter Feb 24 '22 at 14:08
  • Does this answer your question? https://stackoverflow.com/questions/38768737/interaction-between-forms-how-to-change-a-control-of-a-form-from-another-form – Thomas Weller Feb 24 '22 at 14:08
  • 1
    Controls inside a form are defined with the private accessor and accessible only inside the form class. You can change them setting the property _Modifiers_ to public, but it is really a bad practice. Instead write a public method inside the called form and return whatever you need from that textbox. IE _mainForm.GimmeTheUrlText();_ – Steve Feb 24 '22 at 14:14

1 Answers1

1

You should really post the error that you're getting. This wouldn't compile for me because you are referencing the URL_BOX the wrong way. You can do this:

var mainForm = Application.OpenForms.OfType<Form1>().Single();
string urlBoxText = mainForm.Controls["URL_BOX"].Text;

Notice, also, that .Text does not require parenthesis, as it is a property and not a method.

  • Should be `.SingleOrDefault()` or `.FirstOrDefault()`, then test for `null` before anything else. -- This code also assumes that the Control is direct child of a Form, which may not be (the child Control could also be *moved around* while perfecting the design). -- The correct way is described by Steve in comments. It could be either a public method or a public property. – Jimi Feb 24 '22 at 15:19