Skip to content

[C#] Change ctrl text from static void?

sancho

Asked Nov 7, 2008, 4:53 AM EST1 answer
Share
LinkedInX
How could i change a label (or textbox or whatever) .Text from a static void? i have tried calling an instance of the form containing the label but that doesnt work

here are some of the codes i tried, all do the same, shows no error (im not catching ex anyway) and the label.Text never changes.

Code:
C#
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        public static void Count()
        {
            Form1 frm;
            frm = new Form1();
            for (int count = 1; count <= 5; count++)
            {
                //frm.label1.Text = count.ToString();
                frm.label1.Text = "something";
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Count();
        }
}


Code:
C#
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        public static void Count()
        {
            Form1 frm;
            frm = new Form1();
            for (int count = 1; count <= 5; count++)
            {
                //frm.Lbl = count.ToString();
                frm.Lbl = "something";
            }
        }

        public string Lbl
        {
            get
            {
                return label1.Text;
            }
            set
            {
                label1.Text = value;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Count();
        }
}


both codes does the same, they compile ok, show no fatal error but the label never change the .Text

Please help me with this, i already lost an entire day trying to achieve it lol!
thnkx in advance

ps. i forgot to add that the "Count" is just for testing, the static method will be a thread for a multithreading app, thats why it needs to be static.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • +1
    I finally understand how it works, an instance method can call a static, but a static cannot call an instance, so i just need to create the instance and pass it as a param to the count()
    :)
    +1