deleyd
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);
}
}
}
and it goes on like that for
TextBox3
TextBox4
Label1
Label2
etc...
So much repeated code...ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
ASKER