MariusG96
MariusG96

Reputation: 87

Form events used from another class

Is there any way to store the code below in another class called RecordAddControl?

Code from "RecordAdd.cs"

private void txtEilesNum_Enter(object sender, EventArgs e)
{
    txtEilesNum.Clear();
    txtEilesNum.ForeColor = SystemColors.Desktop;
}

private void txtEilesNum_Leave(object sender, EventArgs e)
{
    if (txtEilesNum.Text == "")
    {
        txtEilesNum.ForeColor = SystemColors.InactiveCaption;
        txtEilesNum.Text = "Eil Num";
    }
}

Things I've tried like RecordAdd recordAdd = new RecordAdd(); doesn't seem to work when trying to get the class to recognise things like txtEilesNum.

RecordAdd is a form, and txtEilesNum is taken from "RecordAdd.Designer.cs"

Upvotes: 0

Views: 54

Answers (2)

ASh
ASh

Reputation: 35681

it makes more sense to tailor helper class to work with TextBox directly (any TextBox, not only the one in RecordAdd)

public static class TexBoxDecorator
{
    public static void UsePlaceholder(this TextBox tb)
    {
        tb.Enter += tb_Enter;
        tb.Leave += tb_Leave;
    }

    private static void tb_Enter(object sender, EventArgs e)
    {
        var tb = (TextBox)sender;
        tb.Clear();
        tb.ForeColor = SystemColors.Desktop;
    }

    private static void tb_Leave(object sender, EventArgs e)
    {
        var tb = (TextBox)sender;
        if (tb.Text == "")
        {
            tb.ForeColor = SystemColors.InactiveCaption;
            tb.Text = "Eil Num";
        }
    }
}

txtEilesNum in a known member in RecordAdd, so it can be accessed to add event handlers:

txtEilesNum.UsePlaceholder();

Upvotes: 1

Jamiec
Jamiec

Reputation: 136094

Sure, you can store event handlers in another class, you'll need to make them public, and you'll need to cast the sender to the correct type:

public static class EventHandlers
{
    public void EilesNum_Enter(object sender, EventArgs e)
    {
        var txtEilesNum = (TextBox)sender; // Assumed textbox
        txtEilesNum.Clear();
        txtEilesNum.ForeColor = SystemColors.Desktop;
    }
    public void EilesNum_Leave(object sender, EventArgs e)
    {
        var txtEilesNum = (TextBox)sender; // Also assumed textbox
        if(txtEilesNum.Text == "")
        {
            txtEilesNum.ForeColor = SystemColors.InactiveCaption;
            txtEilesNum.Text = "Eil Num";
        }
    }
}

In your form, you'll still need to wire up the events as before

txtEilesNum.Enter += EventHandlers.EilesNum_Enter;
txtEilesNum.Leave += EventHandlers.EilesNum_Leave;

Upvotes: 0

Related Questions