给标签.运行时用户控件新值中的文本



我是一名学徒,学习c#。在我当前的项目中,我必须学习有关"用户控制"和"拖放"的基础知识。作为我项目的主题,我选择为我最喜欢的足球队做一个基本的团队管理工具。

我想,我会在用户控件中加载玩家数据/统计信息,并将用户控件添加到流布局面板。

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:'对象引用未设置为对象的实例。

我习惯于创建这样的属性:

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

当编译器编译设置部分时,会发生异常。 (是的,在像上面那样完成的每个属性中(

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

编辑:附加信息

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

我终于发现了问题所在。用户控件的构造函数不同于类之一。用户控件中的每个构造函数都需要"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;
    }

谢谢罗特姆和苏尼尔。

最新更新