开发者

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 ?


You mean the Name property?

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


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜