Amadeus45
Amadeus45

Reputation: 1228

How can I find a parameter's original variable name as a string at runtime?

I got in Form_Load :

for (int i = 1; i < 10; i++)
            {
                this.Controls["txtPrix"+i].Enter += new EventHandler(DlgFacture_Enter);
            }

I got the event :

    void DlgFacture_Enter(object sender, EventArgs e)
    {
        this.setTextBoxPrixEnter((TextBox)sender);
    }

In that last event, I want to be able to print the TextBox root variable name (thus txtPrix1 to txtPrix10) as a string, depending on which one calls the event.

How can that be done ?

Upvotes: 1

Views: 116

Answers (2)

RvdK
RvdK

Reputation: 19800

You mean the Name property?

this.setTextBoxPrixEnter(((TextBox)sender).Name);

Upvotes: 2

JaredPar
JaredPar

Reputation: 755269

Not easily. What you're attempting to do is print the name of a reference to an object at runtime. There can be many references to a given object so printing one in the abstract is not possible.

What you would have to do is wrap the Enter handler with a new method that captures the variable name and passes it along.

For example:

var name = "txtPrix"+i;
Controls[name].Enter += (sender,e) => DlgFacture_Enter(name, sender, e);

void DlgFacture_Enter(string name, object sender)
{
    this.setTextBoxPrixEnter((TextBox)sender);
}

Upvotes: 0

Related Questions