Search code examples
c#winformsoopuser-controls

Give label.Text in User Control new value at runtime


I'm an apprentice learning c#. In my current project I must learn the basics about "User Control" and "Drag and Drop". As the topic for my project I have chosen to do a basic team administration tool for my favorite football team.

I thought, that I would load a players data/stats in a user control and add the user control to a flowlayoutpanel.

Players players = new Players();
foreach (Player player in players.GetActive())
{
    flowLayoutPanel1.Controls.Add(new UCPlayer(player.ImageKey,player.Number, player.Name, player.Position, player.Rating
}

Now, when the program tries to change the text of a label in the user control, I get the following exception: "System.NullReferenceException: 'Object reference not set to an instance of an object.'"

I'm used to make properties like this:

public string Name { get; set; }

But in the user control i did it like this:

public int Number
    {
        get { return Convert.ToInt32(this.UCMLBNumber.Text); }
        set { this.UCMLBNumber.Text = value.ToString(); }
    }

public string Name
    {
        get { return this.UCMLBName.Text; }
        set { this.UCMLBName.Text = value; }
    }

The exception occurs, when the compiler compiles the set part. (Yes, in every property done like the ones above)

I don't get, what i did wrong. Please help me. Just ask, if you need any additional information.

Edit: Additional informations

public UCPlayer()
    {
        InitializeComponent();
        this.ImageIndex = 0;
        this.Number = 0;
        this.Nname = string.Empty;
        this.Position = string.Empty;
        this.Rating = 0;
    }

        public UCPlayer(int _imageIndex, int _number, string _name, string _position, int _rating)
    {
        this.ImageIndex = _imageIndex;
        this.Number = _number;
        this.Nname = _name;
        this.Position = _position;
        this.Rating = _rating;
    }

Solution

  • I finally found out, what the problem was. The constructor of a user control differs to one of a class. Every constructor in a user control needs "InitializeComponents();".

    From:

    public UCPlayer(int _imageIndex, int _number, string _name, string _position, int _rating)
        {
            this.ImageIndex = _imageIndex;
            this.Number = _number;
            this.Nname = _name;
            this.Position = _position;
            this.Rating = _rating;
        }
    

    To:

    public UCPlayer(int _imageIndex, int _number, string _name, string _position, int _rating)
        {
            InitializeComponent();
            this.ImageIndex = _imageIndex;
            this.Number = _number;
            this.Nname = _name;
            this.Position = _position;
            this.Rating = _rating;
        }
    

    Thank you Rotem and Sunil.