Trouble with ShowDialog

  • Thread starter Thread starter Dom
  • Start date Start date
D

Dom

I have a Main form called frmMain which appears when the program
starts, and a second form called frmUserName. frmMain has a button,
btnUserName. When you click it, I have this code:

frmUserName f = new frmUserName ();
f.ShowDialog(this);

For the next line, I expected to find f.txtUserName in the
IntelliSense window, but it's not there. In fact, noneof the controls
are there. Am I just caught in VB think?

Dom
 
By default controls are private to a form. See the Modifiers property. You
could change this property for the control in question, but I don't think
that's very good practice. Instead, consider adding a parameter to the
form's constructor that receives a user name. That form's constructor would
then assign the received value to its textbox. You would instantiate your
form like this:
 
Dom,

Yes, you are thinking in VB.

By default, when adding controls to forms, the fields are added as
private. In the designer, you should go to the control and set the
visiblity (or accessiblity, it's something similar) from private to public.

However, I would say that this is a very, very bad idea from a design
standpoint. Rather, just expose properties that expose the details that you
are looking for and have the properties return them from the controls, if
you must.
 
I'll assume that txtUserName is your TextBox? The fields are private
to the class. You can expose them as public, but this is not good
practice; a better approach is a public property to maintain
encapsulation, e.g.

public class frmUserName : ... {
public string UserName {
get {return txtUserName.Text;}
}
...
}

Nowyou should be able to access f.UserName; additionally, you might
want to ensure that this Form gets Dispose()d in a timely fashion:

string username;
using(frmUserName f = new frmUserName()) {
f.ShowDialog(this);
username = f.UserName;
}
// now use username

Marc
 
Back
Top