【问题标题】:How to change button text in a user control using constructor c#?如何使用构造函数 c# 更改用户控件中的按钮文本?
【发布时间】:2018-07-01 01:01:13
【问题描述】:

我已经制作了这个包含按钮的用户控件

using System.Windows.Forms;
namespace test2
{
public partial class testme : UserControl
{
    public testme()
    {
        InitializeComponent();
    }
    public testme(string x)
    {
        button1.Text = x;
    }
}
}

然后我正在尝试使用构造函数更改用户控件中的按钮

using System;
using System.Windows.Forms;
namespace test2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        testme v = new testme("New Text");

}
}
}

但是当我在运行时单击 button1 时,我收到此错误消息 对象引用未设置为对象的实例

【问题讨论】:

    标签: c# .net winforms user-controls


    【解决方案1】:

    重载的构造函数需要调用带有InitializeComponent();的构造函数,称为Constructor Chaining,改这行:

    public testme(string x) : this()
    

    【讨论】:

    • 错误消失但按钮文字没有改变
    • 公共部分类 testme : UserControl { public testme() { InitializeComponent(); } public testme(string x) : this () { button1.Text = x; }
    • 那是因为你已经实例化了一个用户控件但是那个控件还没有被添加到Form中。在button_click中添加testme控件到表单中:this.Controls.Add(v);
    猜你喜欢
    • 2018-12-23
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多