Peter Sun
Peter Sun

Reputation: 1813

C# sharing form data with a class

This is a kind of a newbie question. I haven't done C# programming in a while especially with creating with custom classes. I want to share some data between my forms, I was thinking of creating a class,

public class User
{
    public string id;
    public string name;

    public User()
    {
    }

    public User(string id, string name)
    {
        this.id = id;
        this.name = name;
    }
}

Does the class have to be in a separate file (User.cs)?

If I had the following code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        User user1 = new User("abc","cde");
    }
}

    public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();

    }
}

How should I create the class in Form1 and how should I access it in Form2?

Upvotes: 0

Views: 1971

Answers (6)

Todd Richardson
Todd Richardson

Reputation: 1129

I'm speaking purely from a "I think I've been down the same road you're going down" point of view.

It might be time to break down your application into some patterns. A User class is usually a special kind of entity within an application. In typical cases, it can define the attributes of a user, or it can be used to define the Identity and Claims for a particular user, or all of the above.

It would be good to make a service or utility class for your user. If any given Form, or class for that matter, in your application needs to have information about a User, your service is there to answer the call. This service could provide a CurrentUser property which would inform other classes that the currently logged in user is (null | Bob | xyz...) It can perform validation, access background utilities to cache attributes about the user. but I digress. While writing my answer, @Iker Ruiz Amauda has given a practical example of how might implement this service.

As to how to make this available across your application: it depends on the magnitude of your project. I've like Dependency Injection as mentioned by Karl Anderson. To go along with Dependency Injection would be Inversion of control (IoC). My current flavor of IoC is MEF (http://mef.codeplex.com/documentation). By defining an IUserService that is implemented by UserService, you can "Inject" this service into any form that relies on the userservice. In my current project this is achieved practically using attributes to export and import items.

For more information on Inversion of Control (I think Dependency Injection is pretty straight forward but Google is your friend on that one,) see This answer on stack overflow:

https://stackoverflow.com/a/3140/93964

or this was a decent blog entry I found while google the subject:

http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/

Upvotes: 0

user2259020
user2259020

Reputation:

How you distribute the classes ove files its all up to you. In this example I made you could have UserHandler.cs, User.cs, Form1.cs & Form2.cs. Hope it helps.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public static class UserHandler
    {
        private static  List<User> Users = new List<User>();

        public static void AddNewUser(User user)
        {
            Users.Add(user);
        }

        public static void RemoveUser(User user)
        {
            Users.Remove(user);
        }

        public static User GetUserById(int id)
        {
            if(Users.Exists(x => x.userId == id))
            {
                return Users.Find(user => user.userId == id);
            }

            return null;
        }
    }

    public class User
    {
        public int userId { get; set; }
        public string userName { get; set; }

        public User(int id, string name)
        {
            this.userId = id;
            this.userName = name;
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            var _user = new User(1,"user2252502");
            UserHandler.AddNewUser(_user);
            MessageBox.Show(UserHandler.GetUserById(1).userName);
            Form2 form2 = new Form2();
        }

    }

    public partial class Form2 : Form
    {
        public Form2()
        {
            MessageBox.Show(UserHandler.GetUserById(1).userName);
        }
    }
}

Upvotes: 2

Khan
Khan

Reputation: 18142

How should I create the class in Form1 and How should I access it in Form 2?

This depends on its use. Since your desire is to share it between forms, I am assuming you would like its scope to be class wide. Define it as a class property. Preferably above your constructor for Form1.

Does the class have to be in a separate file, User.cs If I had the following code

It does not have to be, but best practice is that it is.

How do I share it with Form2?

A. Make it a parameter of the constructor of Form2:

public partial class Form2 : Form
{
    public User MyUser { get; set; }

    public Form2(User user)
    {
        InitializeComponent();
        MyUser = user;
    }
}

B. Make it a public property of Form2 and set it from Form1

var frm2 = new Form2();
frm2.User = user;

Upvotes: 0

Ehsan
Ehsan

Reputation: 32661

There are multiple ways of doing this. one way can be that you pass the class in constructor of Form2. like below.

public partial class Form1 : Form
{
    User user1 = new User("abc","cde");
    public Form1()
    {
        InitializeComponent();
        new Form2(user1);
    }
}

public partial class Form2 : Form
{
    User user1;
    public Form2(User u)
    {
        InitializeComponent();
        user1 = u;    
    }
}

Other ways of doing this can be to expose a public property in form1 that returns User. and you access that property in Form2.

Upvotes: 1

Karl Anderson
Karl Anderson

Reputation: 34846

Typically, you separate classes out into separate files, so I would suggest making a User.cs file that contains the User class.

How you are instantiating the class in Form1 is fine, but to get the instance of the class to Form2 you need to pass it to the constructor of Form2, like this:

Form2 theForm2 = new Form2(user1);

Note: To accomplish the code above requires modifying the constructor of Form2, or in this case creating a non-default constructor, and creating a member variable to hold the User class instance, like this:

public partial class Form2 : Form
{
    private User _user;

    public User TheUser
    {
        get
        {
            return _user;
        }
    }

    public Form2()
    {
        InitializeComponent();
    }

    public Form2(User theUser)
    {
        _user = theUser;
    }
}

Now you can use the User class in Form2 by simply referencing the property TheUser.

Upvotes: 2

ganders
ganders

Reputation: 7433

They can be in the same file. If you want to access data from Form1 in Form2, add Form1 as a parameter to the constructor of Form2. Or add it as a property in Form2 and allow it to be "set".

Upvotes: 0

Related Questions