Click here to Skip to main content
15,891,751 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have parent form "login" i need to pass the username from login form to all it's child forms.
i tried using constructors and also making making the textbox public of login form.

bt values passes from login to admin form(child form of login)..
and to pass into bookmgmt form (child of admin), same procress needed to be repeated.


Is there any way to pass values from parent to all it's child n sub child's form??

any help would be appreciated!

thanks in advance :)
Posted

Create a static class and store the info to be shared as properties of that class.

EDIT ===============

A static class is initialized at program startup without any code from extrnal objects having to be written to implement the initialization. So, given the floowing class:

C#
public static class Globals
{
    public static string UserID { get; set; }

    Globals()
    {
        UserID = "";
    }
}

When the program starts, the Globals constructor is called, and UserID is initialized to an empty string

To access UserID, you would do this:

C#
if (string.IsNullOrEmpty(Globals.UserID))
{
    // user isn't logged in
}


It's easy, clean, and maintainable. Further, ANY object in the application can use the static Globals object, which means all of your forms can use set/get the public data in Globals.

Yeah, you could use an interface, but that would require you to change all of your existing forms, and then remember that new forms need to inherit the interface. I prefer to use a static class.
 
Share this answer
 
v2
Comments
BillWoodruff 4-Jul-11 6:54am    
+5 I believe you do need to put the 'static' modifier before the name of the static constructor: i.e.: static Globals()
best, Bill
You have to create a Global class, like this
public static bool ValidateId(string UserName, string Password)
{
try
{
DataSet ds = new DataSet();
string SQLCommand = "select user_is_system from UserDetails where User_Name = '" + UserName + "' and User_Password = '" + EncryptDecrypt.Encode(Password) + "'";
SqlDataAdapter Adapter = new SqlDataAdapter(SQLCommand, Globals.ConnectionString);
Adapter.Fill(ds);
Adapter.SelectCommand.Connection.Close();
if (ds.Tables[0].Rows.Count > 0)
{
if (Convert.ToBoolean(ds.Tables[0].Rows[0]["User_is_system"]))
isSystemUser = true;
else
isSystemUser = false;
return true;
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
Now you can fetch your username from this class in any form.
--In form1 load event--
exp: lblStart.Text = " Welcome, " + Globals.UserName;
 
Share this answer
 
v2
You've already been given some workable solutions, but it really depends on how your app is set up. Are the child forms already open? If so then you let them use a delegate to get the info when they need it. If not, they should get the info in their constructor or form loading event.

As mentioned, perhaps you should rethink your design and interaction between the forms.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 3-Jul-11 0:47am    
Agree. Very good note, my 5.
As to the problem itself, please see my answer.
--SA
I think John Simmons has already put you on the right track, but I would like to ask you why you are having a log-in form be the parent of other forms: imho that's an unusual 'architectural' design.

Please give John S. full credit for his answer: what follows is just an elaboration of his suggestion:

Before C# 3, you'd typically write a static property in a static class like this:

public static class PropDemo
{
     private static string _mString;

     public static string MString
     {
       get { return _mString; }
       set { _mString = value; }
     }
}


With C# 3, the compiler will take care of automatically creating the 'backing field' (the variable '_mString' in the example above):

C#
public static class PropDemo
{

     public static string MString { set; get; }
}


And now, you can also have different levels of scope for the 'get and 'set functions of a property:

public static string MString { private set; get;}


Discussion: you could make a public static variable, and use it in either a static class, or a dynamically allocated class; you could also use a public static Property in a dynamically allocated class, but the principle of 'encapsulation' suggests it is best practice to go ahead and create a Property in a static class. Implementing 'validation' inside the 'setter' of a Property is a typical reason for use of a Property rather than a 'global variable.'
 
Share this answer
 
v4
Comments
Uday P.Singh 3-Jul-11 0:41am    
good answer my 5:)
Sergey Alexandrovich Kryukov 3-Jul-11 0:50am    
It is acceptable, but only good enough for simple application. I voted 4.
A safer and more robust way is based on interfaces -- please see my solution.
--SA
First, there is no such thing as parent-child relationships between form (I don't mean MDI children and parent and hope you don't use MDI — it is strongly discouraged). Instead, there is Owned and Owner form; this is a relationship I strongly recommend to use. There is one more thing — one form is the main one. I would recommend you always make main form the owner of all other (non-modal) forms. This relationship affect form activation: they start to behave as a single application.

Now, how to communicate? This is a popular question about form collaboration. The most robust way it implementing appropriate interface in the form class. For more on this approach, please see my past solution here: How to copy all the items between listboxes in two forms[^].

I agree with Walt, perhaps you should rethink your design. Prefer a single form design, make what was your other form some controls. For example, use tabbed UI based on TabControl.

—SA
 
Share this answer
 
v3
Comments
BillWoodruff 4-Jul-11 7:31am    
"there is not such thing as parent-child relationships between form" You are incorrect. And, the use of a parent-child relationship between Forms, while usually associated, in practice, with MDI architecture is NOT dependent on MDI architecture.

In fact MDI architecture (may it rest in peace in the cemetery of GUI dinosaurs) :), has a its own 'vocabulary' of primitives for setting MDIParent, and MDIChild properties.

A Form whose 'TopLevel' property is set to 'False' can be made the child form of another Form. All Forms expose a 'Parent' property. A Form which is a 'child' of another Form is clipped to the boundaries of its 'parent' Form at run-time.

Where you and I (almost certainly) agree, is that in practice it is very rare to set Forms as children of other Forms, and I can't think of one instance where I've ever done that.

And we certainly agree, I believe, that making use of the Owner/Owned relationship can be valuable, and that MDI architecture is déclassé.

I make these points not to deprecate your obvious technical accomplishments and contributions to CP !

respectfully, Bill
Sergey Alexandrovich Kryukov 5-Jul-11 1:28am    
Hi Bill,

I appreciate your response. To me, what you describe is not parent-child relationship. First of all, did we exclude MDI relationships? I made a note from the very beginning that I don't take them into consideration. If I did you should have admitted them as real parent-child relationship, of course. So, we not arguing about them, let's just forget them.

Now, the Parent property is defunct for the Form. It is just inherited from Control. Is you assign Parent to some form, what happens is ArgumentException "Top-level control cannot be added to control". I tried it. Probably it was possible in earlier versions of .NET, I don't know. You can try to reproduce what I did by yourself and check up my statement -- it will throw exception.

What you call "in practice is very rare" is maybe another technique: you can PInvoke raw Windows API SetParent. In this case you really can stick one form into another. This is not really a part of .NET, nor its intentional behavior. Pure .NET API is guarded against such behavior.

Now, the parent of the instance of the non-form control can be a form. But this is parent-child relationship between a non-form control and a form.

Even thought I seen to disprove your main point of your argument, I think we have been very well agree in most aspects of the topic. You still have to re-validate my statement about a form being a parent of another form. Please do and tell me if you finally agree or not.

I think this is a very useful discussion promoting better understanding of things.

Thank you.
--SA
BillWoodruff 3-Aug-11 8:47am    
Hi SA,

Sorry for the long response time, somehow I missed your comment.

No, the 'Parent property is not defunct for Windows Forms ! It's been there from .NET 1.0~4.0. Whether or not it's 'deprecated' is something I am not totally clear on: while I know I will not use it as part of an 'architecture' of an application, I haven't seen anything from a Grand Poobah at MS; by contrast, it seems to me that MDI is well-known to deprecated.

It has always been the case that a Form made a child of another Form via a call like: someChildForm.Parent = someParentForm cannot have its TopLevel property set to 'true, and this error will not be caught at compile time: at run-time the error will be 'System.ArgumentException.'

The 'TopLevel property is, however, not settable at design-time, and Forms are 'TopLevel = 'true by default, which is a source of confusion for some. Also confusing to some is the presence of a 'TopMost property ... that is editable at design-time ... that has no interaction with the 'TopLevel property.

The 'TopLevel property is both set/get: you can use it to dynamically read-out the value.

Curiously, MS also provides 'protected' methods: someForm.GetTopLevel() duplicates the 'TopLevel property result. And there is a a matching 'SetTopLevel() method. These methods can only be used in your win form app on the Main Form, and will throw a compile error if you attempt to use them on a Form that has been set a child of the Main Form. I assume these are used in sub-classing, or, internally for MDI (?), and over-riding, but I don't know for sure: I've never used them.

You can even 'get away with' nesting multiple levels of Forms within Forms, though I wouldn't do that, and I bet you wouldn't do that :)

In this area of .NET and WinForms, as in other areas, it would be interesting to know what the intent of the designers was, what scenarios ... other than MDI ... they anticipated a programmer using 'TopLevel,' Get/Set/TopLevel.

best, Bill
i was saying login form as parent becoz i wanted the name of user logged in all the other forms.

each form has a label showing the name of the user logged in.

actually i had implemented constructor for this process. but was needing another solutions.
N i don't want mdi.

can anyone post code snippet for using delegate.

thanks all for the replies.
 
Share this answer
 
Comments
#realJSOP 3-Jul-11 8:22am    
I told you how to do it. It would involve no constructor modifications at all. A public static class is the best vehicle for sharing data between disparate objects in an application. I do it ALL THE TIME.
sanomama 3-Jul-11 9:00am    
thanks i will try it

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900