Question

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?

Was it helpful?

Solution

I think this line will do the trick for you:

window.LocationChanged += new EventHandler(delegate(object o, EventArgs evtArgs) { 
    label.Text = window.Location.ToString(); 
});

OTHER TIPS

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? :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top