Author Topic: Having problem with class inhetitage  (Read 1146 times)

0 Members and 1 Guest are viewing this topic.

ekoneo

  • Newt
  • Posts: 66
Having problem with class inhetitage
« 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.

« Last Edit: October 19, 2021, 03:37:46 AM by ekoneo »

MickD

  • King Gator
  • Posts: 3636
  • (x-in)->[process]->(y-out) ... simples!
Re: Having problem with class inhetitage
« Reply #1 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.  
"Programming is really just the mundane aspect of expressing a solution to a problem."
- John Carmack

"Short cuts make long delays,' argued Pippin.”
- J.R.R. Tolkien