user3877230
user3877230

Reputation: 458

Change Textfield from another class?

I start out with my sourcecode:

FORM

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace software
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        try
        {
            MyClassTwo two = new MyClassTwo();
two.putValue();
        }
        catch
        {
            MessageBox.show("Error!");
        }
    }
}

MyClassTwo

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace software
{
    public class MyClassTwo
    {
        Form1 myForm = new Form1();

        public void putValue()
        {
            myForm.textbox1.Text = "Hello";
        }
    }
}

I want to change the content of the textbox in MyClassOne. When i do it like this it doesnt work, just nothing happens. Can anyone help me with that? I updated the code.

Upvotes: 0

Views: 39

Answers (1)

psoshmo
psoshmo

Reputation: 1550

The form that your MyClassTwo is referring to is not the same form as the one you are trying to set the text in. Your MyClassTwo is creating an entirely new instance of the Form and setting the text of that, which you never see.

without trying toooo hard, could you try something like this?

public class MyClassTwo
{

    public void putValue(Form1 myForm)
    {
        myForm.textbox1.Text = "Hello";
    }
}

and

 try
    {
        MyClassTwo two = new MyClassTwo();
        two.putValue(this);
    }

The idea is simply to pass the form that you want to change the text in, opposed to creating a new form inside of MyClassTwo.

Upvotes: 1

Related Questions