DonationCoder.com forum
 
Read-only archive. This is a static copy of the DonationCoder.com forum. Reading and searching work as before; logging in, posting and private messages do not.
Archive of 2026-10-21 · About this archive · Main site

Author Topic: Writing to Form1 textbox from Form2  (Read 12,663 times)

Beatz

  • Participant
  • Joined in 2011
  • *
  • Posts: 1
Writing to Form1 textbox from Form2
« on: November 21, 2011, 04:22 AM »
Umm just wondering if anyone could help me I am trying to write to form2.AutoRunCommand to Form1.Textbox to write ("AutoRunCommand initiated"); or something of the sort

Example

Spoiler (click to show/hide)
Form1

TextBox.AppendText("Program has started\n");


A .cs (NOT a Form)

public void AutoRunInitiated()
{
Form1.TextBox.AppentText("Autorun has been initiated\n");
}

A .cs (NOT a Form)

public void AnotherProcessStarts()
{
Form1.TextBox.AppentText("Another process has started\n");
}

Sorry if its not too clear what I want I am not so good at explaining stuff :)

Thanks in advance for any help
« Last Edit: November 21, 2011, 06:18 AM by Beatz »

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • Participated in NANY Challenge Eight Times
    • Programming School - Deluxe Bonus Medal
    • Programming School - Stage 1 Medal
    • Coding Snacks
    • Military Service Badge - US Army
    • Writer
Re: Writing to Form1 textbox from Form2
« Reply #1 on: November 25, 2011, 04:14 AM »
See this post on my blog.  It demonstrates setting up some properties in the "sending" form, then passing a reference to Form1 into Form2's constructor and utilizing those properties.  You're desired behavior calls for a similar approach.
Win 10 Pro running on a 3.2 GHz CPU and 12 Gb RAM
__________________________________________

Proofreading Service: http://williammillerservices.com/proofreading

f0dder

  • [Well, THAT escalated quickly!]
  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,153
    • Participated in NANY Challenge Once
Re: Writing to Form1 textbox from Form2
« Reply #2 on: November 26, 2011, 04:41 PM »
Ideally, your forms really shouldn't know about eachother - but "forms based" programming usually means lots of intertangled junky code, especially if you're a novice programmer who picked up a rapid interface design environment.

Nothing wrong with that, but if you want to do more than small programs, you need to learn proper program design :). In the short term, passing form instances around to constructors and whatnot will work, but it's not good for modularity, re-use, or being able to comprehend your code a few months from now.

The first thing you need to learn is separating your GUI from your "real code". This means having pretty much all your logic separated from the GUI code, and never directly referencing GUI controls from the logic/model code. Let your GUI controls observe your program's model state, and let GUI events be very shallow things doing little else but delegating to instance calls on your model.
- carpe noctem

wraith808

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 11,205
    • Participated in NANY Challenge Fourteen Times
    • Coding Snacks
    • Writer
    • Hardware Hacker
Re: Writing to Form1 textbox from Form2
« Reply #3 on: November 26, 2011, 09:44 PM »
^ +1.  I was just going to say that, but was coding an example first (needed to test some peripheral things, and needed a test bed, so seemed like the thing to do).

wraith808

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 11,205
    • Participated in NANY Challenge Fourteen Times
    • Coding Snacks
    • Writer
    • Hardware Hacker
Re: Writing to Form1 textbox from Form2
« Reply #4 on: November 27, 2011, 05:25 AM »
Remember, this is from an unrelated project, but I shoehorned this in.  It won't compile as is, because some code I can't distribute is needed.  I also replaced some functional code with placeholder code.  But it should get the general idea across.

View Class
Code: (csharp)
    public partial class WorkerClassView : Window
    {
        private WorkerClassViewModel ViewModel { get; set; }

        public WorkerClassView()
        {
            InitializeComponent();

            this.ProgressEvent = this.OnProgress;
            pbrStatus.Maximum = 100;
            pbrStatus.Minimum = 0;

            this.ViewModel = new WorkerClassViewModel(this.ProgressEvent);
            this.DataContext = this.ViewModel;
            this.Loaded += new RoutedEventHandler(WorkerClassView_Loaded);
        }

        private void WorkerClassView_Loaded(object sender, RoutedEventArgs e)
        {
            var inputBindings = new InputBindingCollection();

            inputBindings.Add(new InputBinding(this.ViewModel.StartCommand, new KeyGesture(Key.S, ModifierKeys.Control | ModifierKeys.Alt)));
        }

        private ProgressChangedEventHandler ProgressEvent;

        private void OnProgress(object sender, ProgressChangedEventArgs e)
        {
            pbrStatus.Value = e.ProgressPercentage >= pbrStatus.Minimum && e.ProgressPercentage <= pbrStatus.Maximum ? e.ProgressPercentage : 0;
            pbrStatus.Refresh();

            txtStatus.Text = e.UserState.ToString();
            txtStatus.Refresh();
        }
    }

Worker Class
Code: (csharp)
    public abstract class WorkerBase: IWorker
    {
        protected string WorkerName 
        { 
            get; 
            private set; 
        }

        public WorkerBase(string workerName) 
        {
            this.WorkerName = workerName;
        }

        public void Execute(ProgressChangedEventHandler callback)
        {
            this.Initialize(callback);
            this.DoWork(callback);
            this.Finalize(callback);
        }

        private void Finalize(ProgressChangedEventHandler callback)
        {
            if (callback != null)
            {
                callback(this, new ProgressChangedEventArgs(100, string.Format("Worker {0} Complete!", this.WorkerName)));
            }
        }

        protected abstract void DoWork(ProgressChangedEventHandler callback);

        private void Initialize(ProgressChangedEventHandler callback)
        {
            if (callback != null)
            {
                callback(this, new ProgressChangedEventArgs(0, string.Format("Worker {0} Reporting!", this.WorkerName)));
            }
        }
    }

ViewModel Class
Code: (csharp)
    public class WorkerClassViewModel
    {
        private ProgressChangedEventHandler CallBack = null;

        private bool Executing { get; set; }

        public WorkerClassViewModel(ProgressChangedEventHandler callback)
        {
            this.CallBack = callback;
            this.Executing = false;
            this.StartCommand = new RelayCommand(param => this.StartCommandExecute(), param => this.StartCommandCanExecute);
            this.CloseCommand = new RelayCommand(param => this.CloseCommandExecute(), param => this.CloseCommandCanExecute);
        }

        private void StartWorkers()
        {
            this.Executing = true;
            try
            {
                SimpleWorker workerOne = new SimpleWorker("Discipline");
                SimpleWorker workerTwo = new SimpleWorker("Conviction");

                workerOne.Execute(this.CallBack);
                workerTwo.Execute(this.CallBack);
            }
            finally
            {
                this.Executing = false;
            }
        }

        public ICommand StartCommand
        {
            get;
            private set;
        }

        protected bool StartCommandCanExecute
        {
            get
            {
                return !this.Executing;
            }
        }

        protected void StartCommandExecute()
        {
            this.StartWorkers();
        }

        public ICommand CloseCommand
        {
            get;
            private set;
        }

        protected bool CloseCommandCanExecute
        {
            get
            {
                return !this.Executing;
            }
        }

        protected void CloseCommandExecute()
        {

        }
    }

The View Class (the form) instantiates the ViewModel, and passes it a reference to the callback.  Then when the ViewModel is told to execute, it passes this callback to the workers.  At any of these states, the callback can be done, and the form updated.  Note that as is, the code is NOT threadsafe.  So if you're going to be using it threaded, you'd need to check to see if the UI is getting updated on the UI thread or on a background thread.  If you are using threading, I can point you to a tutorial.  But if you just want to update one form from a process, the callback should be all you need.

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • Participated in NANY Challenge Eight Times
    • Programming School - Deluxe Bonus Medal
    • Programming School - Stage 1 Medal
    • Coding Snacks
    • Military Service Badge - US Army
    • Writer
Re: Writing to Form1 textbox from Form2
« Reply #5 on: December 04, 2011, 01:10 PM »
Quote
In the short term, passing form instances around to constructors and whatnot will work, but it's not good for modularity, re-use, or being able to comprehend your code a few months from now.

The first thing you need to learn is separating your GUI from your "real code". This means having pretty much all your logic separated from the GUI code, and never directly referencing GUI controls from the logic/model code. Let your GUI controls observe your program's model state, and let GUI events be very shallow things doing little else but delegating to instance calls on your model.

Agreed.  :Thmbsup:
Win 10 Pro running on a 3.2 GHz CPU and 12 Gb RAM
__________________________________________

Proofreading Service: http://williammillerservices.com/proofreading

Renegade

  • Tell me something you don't know...
  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 13,291
    • Participated in NANY Challenge Three Times
    • Furry Fandom Badge - Furry Fandom
    • Linux User
Re: Writing to Form1 textbox from Form2
« Reply #6 on: December 04, 2011, 01:31 PM »
Here's another way to do things... Keep in mind that is not appropriate for some things, but depending upon your logic, it can function perfectly fine with much less code.

Use settings. Done.

e.g.

Code: (csharp)
// Set it
Properties.Settings.Default.SomeTypedValue = myvar;

// Get it
mynewvar = Properties.Settings.Default.SomeTypedValue;

You can do that from anywhere in the application.

But, like I said, it's not appropriate all the time. It makes sense in some situations though.

It's kind of abusing the settings, but whatever. If you're careful about what you're doing, it's an incredibly cheap and fast hack to get the job done.

Slow Down Music - Where I commit thought crimes...

Freedom is the right to be wrong, not the right to do wrong. - John Diefenbaker

wraith808

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 11,205
    • Participated in NANY Challenge Fourteen Times
    • Coding Snacks
    • Writer
    • Hardware Hacker
Re: Writing to Form1 textbox from Form2
« Reply #7 on: December 05, 2011, 01:02 AM »
It's kind of abusing the settings, but whatever.

I think I just threw up a little in my mouth. ;)

It creates a large window of exposure, and debugging anything that occurred from that (other than in the simplest case) is going to be a nightmare, IMO.

Renegade

  • Tell me something you don't know...
  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 13,291
    • Participated in NANY Challenge Three Times
    • Furry Fandom Badge - Furry Fandom
    • Linux User
Re: Writing to Form1 textbox from Form2
« Reply #8 on: December 05, 2011, 01:14 AM »
It's kind of abusing the settings, but whatever.

I think I just threw up a little in my mouth. ;)

It creates a large window of exposure, and debugging anything that occurred from that (other than in the simplest case) is going to be a nightmare, IMO.

Not really... Like I said, if the situation is appropriate, then it's ok. Like in the simplest cases. :)

Here's an example.

You have FORM1 where you enter a value then store it. Later, you open FORM2, but need that value. You simply then retrieve it and handle the situation if the value isn't present. The key being that if the value isn't present when you open FORM2, then you should avoid it.

If you need to programmatically create values with both forms open, then it's a bad idea.

Basically, if you need a timer, it's a bad idea and a cheap hack that you should only use for prototyping.


Slow Down Music - Where I commit thought crimes...

Freedom is the right to be wrong, not the right to do wrong. - John Diefenbaker

wraith808

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 11,205
    • Participated in NANY Challenge Fourteen Times
    • Coding Snacks
    • Writer
    • Hardware Hacker
Re: Writing to Form1 textbox from Form2
« Reply #9 on: December 05, 2011, 02:12 AM »
^ OK.  I can go with that. :)

Renegade

  • Tell me something you don't know...
  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 13,291
    • Participated in NANY Challenge Three Times
    • Furry Fandom Badge - Furry Fandom
    • Linux User
Re: Writing to Form1 textbox from Form2
« Reply #10 on: December 05, 2011, 02:32 AM »
^ OK.  I can go with that. :)

I probably should have been clearer about when it's a good/bad idea to do that.

I think it's a fantastic trick for prototyping though. For the sake of a half dozen lines of code, you can "get it working" and have a look-feel before you rip it out and scrap the idea or move on and replace it with the kind of code that you posted above.

Admittedly, I use it for quickly prototyping.

Slow Down Music - Where I commit thought crimes...

Freedom is the right to be wrong, not the right to do wrong. - John Diefenbaker

f0dder

  • [Well, THAT escalated quickly!]
  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,153
    • Participated in NANY Challenge Once
Re: Writing to Form1 textbox from Form2
« Reply #11 on: December 05, 2011, 09:11 PM »
I probably should have been clearer about when it's a good/bad idea to do that.
Especially since it's in a thread with a question from a design/architecture novice :)
- carpe noctem

wraith808

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 11,205
    • Participated in NANY Challenge Fourteen Times
    • Coding Snacks
    • Writer
    • Hardware Hacker
Re: Writing to Form1 textbox from Form2
« Reply #12 on: December 05, 2011, 09:43 PM »
I probably should have been clearer about when it's a good/bad idea to do that.
Especially since it's in a thread with a question from a design/architecture novice :)

Burn!  :onfire:

(j/k ;D)

Original address: https://www.donationcoder.com/forum/index.php?topic=28744.0