user1937011
user1937011

Reputation:

Passing object between forms in c#

Hy,

I have the following class:

 public class Player
{
    private int score;
    private int mapSize;
    private int wins;
    private int level;
    private int plays;
   // private List<String> Paths { get; set; }
    public String Paths { get; set; }

    public Player()
    {
    }

    public Player(String name)
    {
        Name = name;
    }

    public Player(String name, int score)
    {
        Name = name;
        this.score = score;
    }

    public Player(String name, String Paths, int score, int wins, int plays)
    {
        Name = name;
        this.Paths = Paths;
        this.score = score;
        this.wins = wins;
        this.plays = plays;

    }

    public int Score
    {
        get
        {
            return score;
        }

        set
        {
            score = value;
        }

    }

    public int MapSize
    {
        get
        {
            return mapSize;
        }
        set
        {
            mapSize = value;
        }
    }

    public String Name { get; set; }

....

and one event handler from one form

private void NewGame_Click(object sender, EventArgs e)
{
    MainWin ng = new MainWin(this.Name);

    this.Hide();
    ng.ShowDialog();
    this.Close();

}

I try to send the propriety Name of the object to another form

public MainWin(Player name)
{
    InitializeComponent();
    this.Name = name;
    //nXNToolStripMenuItem
}

But instead for the name I get the error: Cannot implicitly convert type Player to string.

Please help, how I can send object name propriety from one form to another?

Upvotes: 1

Views: 120

Answers (1)

Adil
Adil

Reputation: 148120

The this refers to current form object in the button handler, this.Name is a string but the MainWin the constructor of Form expect Player object, so you need to pass Player class object

private void NewGame_Click(object sender, EventArgs e)
{
    //Player p = new Player(); //Create Player class object
    Player p = new Player(this.Name); //Create Player class object
    MainWin ng = new MainWin(p); //Pass Player class object

    this.Hide();
    ng.ShowDialog();
    this.Close();

}

Upvotes: 2

Related Questions