jay_t55
jay_t55

Reputation: 11662

Getting Selected Control

I have a "canvas" (which is just a Panel Control), and the user can click a button to add certain controls to the canvas i.e. labels, link labels, images etc... And then they can edit those controls, like they can edit the text of the label they just added...

But I'm trying to let them choose a new font and a new color for the control that they clicked on, but it doesn't always work, even though it should be...

the code i have is:

private string SelectedControl;

when i click on a control:

private void label_Click(object sender, EventArgs e)
{
    Label label = (Label)sender;
    SelectedControl = label.Name;
}

when the user selects a font:

private void setfont()
{
    foreach(Control control in Canvas.Controls)
    {
        if(control.Name == SelectedControl)
        {
            control.Font = selectedfont;
        }
    }
}

So, This code does work BUT just not all the time. Does anybody know of any other way to somehow keep track of the Last-Clicked control, so it can be referenced later?

Upvotes: 2

Views: 6346

Answers (1)

Alastair Pitts
Alastair Pitts

Reputation: 19601

instead of storing the string name, why not store a reference to the last clicked control itself?

so your code becomes:

private Control SelectedControl;

private void label_Click(object sender, EventArgs e)
{
    Control ctrl = sender as Control;
    if(ctrl != null)
        SelectedControl = ctrl;
}

private void setfont()
{
    SelectedControl.Font = selectedfont;
}

It costs very little to store a reference, and you can access the reference directly.

EDIT: By changing the reference to being a Control, you are able to reference many different types of controls without having to typecast around. The reason I do this bit of code:

Control ctrl = sender as Control;
if(ctrl != null)
        SelectedControl = ctrl;

is it's a safer typecast. If the sender, for some reason, doesn't inherit from Control, then it won't be typecast and label will be null, but an exception won't be raised.

You could have a single click event handler for all of the controls that you want to be able to be changed via being selected. This will work much easier if you are creating the controls in code and hooking up the events manually.

You may want to look into doing some border or effect to show which control has been selected. This could be performed by doing this:

if(ctrl != null)
{
    Deselect(SelectedControl); //Deselects the old control
    SelectedControl = ctrl;
    Select(SelectedControl); //Selects the new control
}

where Deselect and Select do some fancy effects or border.

Hope this helps.

Upvotes: 3

Related Questions