tags:

views:

238

answers:

2

I have a form which is an MDI container. In that form i generate 6 child forms each with a label:

for (int i = 0; i < 6; i++)
{
 Form window = new Form();
 window.Width = 100;
 window.Height = 100;

 window.MdiParent = this;
 window.FormBorderStyle = FormBorderStyle.FixedToolWindow;

 Label label = new Label();
 label.AutoSize = true;
 label.Location = new System.Drawing.Point(1, 1);
 label.Size = new System.Drawing.Size(35, 13);
 label.TabIndex = 1;
 label.Name = "label" + i.ToString();
 label.Text = window.Top.ToString();

 window.LocationChanged += new System.EventHandler(HERE);

 window.Controls.Add(label);
 window.Show();    
}

I added an event on the locationchanged for window. Now how do do it so that label updates to the windows position?

+1  A: 

I think this line will do the trick for you:

window.LocationChanged += new EventHandler(delegate(object o, EventArgs evtArgs) { 
    label.Text = window.Location.ToString(); 
});
Fredrik Mörk
Works perfectly thanks :)
Ozzy
A: 

Well, it's easiest to do it with a lambda expression or an anonymous method:

window.LocationChanged += (sender, args) => label.Text = window.Top.ToString();

If you're using C# 1.1 you'd need to be a bit trickier because of the label being captured automatically in C# 2+ - you'd have to create a new class like this:

internal class LocationChangeNotifier
{
    private readonly Label label;

    internal LocationChangeNotifier(Label label)
    {
        this.label = label;
    }

    internal void HandleLocationUpdate(object sender, EventArgs e)
    {
        label.Text = ((Control) sender).Top.ToString();
    }
}

then use it as:

LocationChangeNotifier notifier = new LocationChangeNotifier(label);
window.LocationChanged += new EventHandler(notifier.HandleLocationUpdate);

Aren't captured variables great? :)

Jon Skeet
And Jon's solution always have that extra touch of elegance (apart from window.Top not returning the position...) ;o)
Fredrik Mörk
I was assuming that only "top" was wanted, given the original value. It would seem odd to skip from *just* showing the top value to showing the full location. I agree that the question isn't clear though :)
Jon Skeet
True, I actually missed that in the original code sample; interpreted "position" in the text to location in my code; I will blame my sometimes too quick reading along with English not being my mother tongue...
Fredrik Mörk