Link to home
Start Free TrialLog in
Avatar of deleyd
deleydFlag for United States of America

asked on

Delegates everywhere. How to simplify this?

I have a Windows Form with text boxes and labels etc., and each one has it's own method for updating the text. Looks like a lot of duplicate code. Is there a way to simplify this?
delegate void UpdateTextBoxDelegate(string text);

/* Call this method to append text to textBox1 */
public void AppendTextBox1(string text)
{
  // Check if this method is running on a different thread
  if (this.textBox1.InvokeRequired)
  {
    // It's on a different thread, so use Invoke. (We call ourself through a delegate.)
    UpdateTextBoxDelegate d = new UpdateTextBoxDelegate(AppendTextBox1);
    this.textBoxLog.BeginInvoke (d, new object[] { text });
  }
  else
  {
    try
    {
      this.textBox1.AppendText(text + Environment.NewLine);
    }
    catch (Exception e)
    {
      LogMsg("AppendTextBox1: Exception: " + e.Message);
    }
  }
}

/* Call this method to append text to textBox2 */
public void AppendTextBox2(string text)
{
  // Check if this method is running on a different thread
  if (this.textBox2.InvokeRequired)
  {
    // It's on a different thread, so use Invoke. (We call ourself through a delegate.)
    UpdateTextBoxDelegate d = new UpdateTextBoxDelegate(AppendTextBox2);
    this.textBox2.BeginInvoke (d, new object[] { text });
  }
  else
  {
    try
    {
      this.textBox2.AppendText(text + Environment.NewLine);
    }
    catch (Exception e)
    {
      LogMsg("AppendTextBox2: Exception: " + e.Message);
    }
  }
}

Open in new window

and it goes on like that for
TextBox3
TextBox4
Label1
Label2
etc...
So much repeated code...
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of deleyd

ASKER

Love it! It just keeps getting better and better!
Right...he used AppendText() for the TextBox, which isn't available for all controls.  If you are only setting the Text() property then you can make it more generic as EaswaranP suggests.