在运行时在用户控件中赋予 label.Text 新值

Give label.Text in User Control new value at runtime

我是学c#的学徒。 在我当前的项目中,我必须学习 "User Control" 和 "Drag and Drop" 的基础知识。作为我项目的主题,我选择为我最喜欢的足球队做一个基本的团队管理工具。

我想,我会在用户控件中加载播放器 data/stats 并将用户控件添加到流布局面板。

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
}

现在,当程序试图更改用户控件中标签的文本时,出现以下异常:"System.NullReferenceException: 'Object reference not set to an instance of an object.'"

我习惯做这样的属性:

public string Name { get; set; }

但是在用户控件中我是这样做的:

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; }
    }

编译器编译set部分时出现异常。 (是的,在每个 属性 中都像上面那样完成)

我不明白,我做错了什么。请帮我。如果您需要任何其他信息,请直接询问。

编辑:附加信息

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;
    }

我终于找到问题所在了。 用户控件的构造函数与 class 之一不同。用户控件中的每个构造函数都需要 "InitializeComponents();".

发件人:

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;
    }

收件人:

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;
    }

谢谢 Rotem 和 Sunil。