TheSwamp

Code Red => .NET => Topic started by: ekoneo on October 19, 2021, 03:33:28 AM

Title: Having problem with class inhetitage
Post by: ekoneo on October 19, 2021, 03:33:28 AM
I created a Form1 form including a label1. Also I created a class1 file. When Form1 load the startFunction methos will be triggered by the Form1_Load event. startFunction is a inherited method.

Code: [Select]
namespace MyNameSpace
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load (object sender, EventArgs e)
        {

            StartMethod();

        }
        public void startMethod()
        {
            Class1 ClasInherited = new Class1();
            ClasInherited.ChangeLabelText();
         }
.
.

Class1.cs file include ChangeLabelText() method.

Code: [Select]

public partial class Class1
    {
    Form1 form1 = new YuzeyAnaliz();
   
     public void ChangeLabelText()
    {
   
     form1.label5.Text = "Text changed";

    }
.
.



However label5 text doesnt change. I am missing something.

Title: Re: Having problem with class inhetitage
Post by: MickD on October 19, 2021, 04:39:36 PM
You are 'embedding' another form inside the Class1 class, not inheriting Class1

Form1 inherits from Form
Class1 doesn't inherit anything but it does create a Form1 inside itself (encapsulation)

Something like this should work:
Code - C#: [Select]
  1.     public class Form1 : Form
  2.     {
  3.         public Form1() // constructor, you can initialize everything here instead of _Load if you want
  4.         {
  5.             InitializeComponent();
  6.             // you can change text here too
  7.         }
  8.  
  9.         private void Form1_Load(object sender, EventArgs e)
  10.         {
  11.             // _Load good for loading external data say or saved settings when the form is loaded
  12.             StartMethod();
  13.  
  14.             // or just change text here, no need for StartMethod():
  15.             // this.lable5.Text = "Text changed";
  16.         }
  17.  
  18.         public void StartMethod()
  19.         {
  20.             this.lable5.Text = "Text changed";
  21.         }
  22.     }
  23.