ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

Writing to Form1 textbox from Form2

(1/3) > >>

Beatz:
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

SpoilerForm1

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

kyrathaba:
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:
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.

wraith808:
^ +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:
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# ---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: C# ---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: C# ---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.

Navigation

[0] Message Index

[#] Next page

Go to full version