Search code examples
c#.netwinformsuser-controls

How to change button text in a user control using constructor c#?


i have made this user control which contain a Button

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

then i'm trying to change the button in user control using contructor

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");

}
}
}

but when i click at button1 in run time i get this error message Object reference not set to an instance of an object


Solution

  • The overloaded constructor needs to call the constructor with the InitializeComponent();, it's called Constructor Chaining, change this line:

    public testme(string x) : this()