topbanner_forum
  *

avatar image

Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  • Wednesday December 11, 2024, 8:29 am
  • Proudly celebrating 15+ years online.
  • Donate now to become a lifetime supporting member of the site and get a non-expiring license key for all of our programs.
  • donate

Author Topic: Writing to Form1 textbox from Form2  (Read 9880 times)

Beatz

  • Participant
  • Joined in 2011
  • *
  • default avatar
  • Posts: 1
    • View Profile
    • Donate to Member
Writing to Form1 textbox from Form2
« on: November 20, 2011, 10:22 PM »
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
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, 12:18 AM by Beatz »

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #1 on: November 24, 2011, 10:14 PM »
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.

f0dder

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,153
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #2 on: November 26, 2011, 10:41 AM »
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
  • **
  • default avatar
  • Posts: 11,190
    • View Profile
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #3 on: November 26, 2011, 03: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
  • **
  • default avatar
  • Posts: 11,190
    • View Profile
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #4 on: November 26, 2011, 11:25 PM »
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: C# [Select]
  1. public partial class WorkerClassView : Window
  2.     {
  3.         private WorkerClassViewModel ViewModel { get; set; }
  4.  
  5.         public WorkerClassView()
  6.         {
  7.             InitializeComponent();
  8.  
  9.             this.ProgressEvent = this.OnProgress;
  10.             pbrStatus.Maximum = 100;
  11.             pbrStatus.Minimum = 0;
  12.  
  13.             this.ViewModel = new WorkerClassViewModel(this.ProgressEvent);
  14.             this.DataContext = this.ViewModel;
  15.             this.Loaded += new RoutedEventHandler(WorkerClassView_Loaded);
  16.         }
  17.  
  18.         private void WorkerClassView_Loaded(object sender, RoutedEventArgs e)
  19.         {
  20.             var inputBindings = new InputBindingCollection();
  21.  
  22.             inputBindings.Add(new InputBinding(this.ViewModel.StartCommand, new KeyGesture(Key.S, ModifierKeys.Control | ModifierKeys.Alt)));
  23.         }
  24.  
  25.         private ProgressChangedEventHandler ProgressEvent;
  26.  
  27.         private void OnProgress(object sender, ProgressChangedEventArgs e)
  28.         {
  29.             pbrStatus.Value = e.ProgressPercentage >= pbrStatus.Minimum && e.ProgressPercentage <= pbrStatus.Maximum ? e.ProgressPercentage : 0;
  30.             pbrStatus.Refresh();
  31.  
  32.             txtStatus.Text = e.UserState.ToString();
  33.             txtStatus.Refresh();
  34.         }
  35.     }

Worker Class
Code: C# [Select]
  1. public abstract class WorkerBase: IWorker
  2.     {
  3.         protected string WorkerName
  4.         {
  5.             get;
  6.             private set;
  7.         }
  8.  
  9.         public WorkerBase(string workerName)
  10.         {
  11.             this.WorkerName = workerName;
  12.         }
  13.  
  14.         public void Execute(ProgressChangedEventHandler callback)
  15.         {
  16.             this.Initialize(callback);
  17.             this.DoWork(callback);
  18.             this.Finalize(callback);
  19.         }
  20.  
  21.         private void Finalize(ProgressChangedEventHandler callback)
  22.         {
  23.             if (callback != null)
  24.             {
  25.                 callback(this, new ProgressChangedEventArgs(100, string.Format("Worker {0} Complete!", this.WorkerName)));
  26.             }
  27.         }
  28.  
  29.         protected abstract void DoWork(ProgressChangedEventHandler callback);
  30.  
  31.         private void Initialize(ProgressChangedEventHandler callback)
  32.         {
  33.             if (callback != null)
  34.             {
  35.                 callback(this, new ProgressChangedEventArgs(0, string.Format("Worker {0} Reporting!", this.WorkerName)));
  36.             }
  37.         }
  38.     }

ViewModel Class
Code: C# [Select]
  1. public class WorkerClassViewModel
  2.     {
  3.         private ProgressChangedEventHandler CallBack = null;
  4.  
  5.         private bool Executing { get; set; }
  6.  
  7.         public WorkerClassViewModel(ProgressChangedEventHandler callback)
  8.         {
  9.             this.CallBack = callback;
  10.             this.Executing = false;
  11.             this.StartCommand = new RelayCommand(param => this.StartCommandExecute(), param => this.StartCommandCanExecute);
  12.             this.CloseCommand = new RelayCommand(param => this.CloseCommandExecute(), param => this.CloseCommandCanExecute);
  13.         }
  14.  
  15.         private void StartWorkers()
  16.         {
  17.             this.Executing = true;
  18.             try
  19.             {
  20.                 SimpleWorker workerOne = new SimpleWorker("Discipline");
  21.                 SimpleWorker workerTwo = new SimpleWorker("Conviction");
  22.  
  23.                 workerOne.Execute(this.CallBack);
  24.                 workerTwo.Execute(this.CallBack);
  25.             }
  26.             finally
  27.             {
  28.                 this.Executing = false;
  29.             }
  30.         }
  31.  
  32.         public ICommand StartCommand
  33.         {
  34.             get;
  35.             private set;
  36.         }
  37.  
  38.         protected bool StartCommandCanExecute
  39.         {
  40.             get
  41.             {
  42.                 return !this.Executing;
  43.             }
  44.         }
  45.  
  46.         protected void StartCommandExecute()
  47.         {
  48.             this.StartWorkers();
  49.         }
  50.  
  51.         public ICommand CloseCommand
  52.         {
  53.             get;
  54.             private set;
  55.         }
  56.  
  57.         protected bool CloseCommandCanExecute
  58.         {
  59.             get
  60.             {
  61.                 return !this.Executing;
  62.             }
  63.         }
  64.  
  65.         protected void CloseCommandExecute()
  66.         {
  67.  
  68.         }
  69.     }

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
    • View Profile
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #5 on: December 04, 2011, 07:10 AM »
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:

Renegade

  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 13,291
  • Tell me something you don't know...
    • View Profile
    • Renegade Minds
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #6 on: December 04, 2011, 07:31 AM »
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: C# [Select]
  1. // Set it
  2. Properties.Settings.Default.SomeTypedValue = myvar;
  3.  
  4. // Get it
  5. 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
  • **
  • default avatar
  • Posts: 11,190
    • View Profile
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #7 on: December 04, 2011, 07:02 PM »
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

  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 13,291
  • Tell me something you don't know...
    • View Profile
    • Renegade Minds
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #8 on: December 04, 2011, 07:14 PM »
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
  • **
  • default avatar
  • Posts: 11,190
    • View Profile
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #9 on: December 04, 2011, 08:12 PM »
^ OK.  I can go with that. :)

Renegade

  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 13,291
  • Tell me something you don't know...
    • View Profile
    • Renegade Minds
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #10 on: December 04, 2011, 08:32 PM »
^ 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

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,153
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #11 on: December 05, 2011, 03: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
  • **
  • default avatar
  • Posts: 11,190
    • View Profile
    • Donate to Member
Re: Writing to Form1 textbox from Form2
« Reply #12 on: December 05, 2011, 03: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)