這聽起來像你有所有的作品,只需要幫助把它放在一起。對於ControlName,您可以將發件人對象轉換爲控件並訪問其Name屬性。
void SetProperty(Control ctr)
{
foreach (Control control in ctr.Controls)
{
if (control is TextBox)
{
control.Leave += control_Leave;
}
else
{
if (control.HasChildren)
{
SetProperty(control);
}
}
}
}
void control_Leave(object sender, EventArgs e)
{
var textBox = sender as TextBox;
Double value;
if (Double.TryParse(textBox.Text, out value))
textBox.Text = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C2}", value);
else
textBox.Text = String.Empty;
}
用法:
SetProperty(this);
而且,從我在OP評論:如果會計是真正重要的,我會建議使用十進制類型,而不是雙。 Double會更快,但Decimal更精確。找出哪種權衡是合理的,並據此作出決定。每評論
編輯:
myTextBox.Leave -= control_Leave
如果你知道控件的名字,上面會工作。在使用SetProperty(this)之後,您將需要執行此操作。如果你想在SetProperty()方法中處理這個,請檢查control.Name ==「myTextBox」。
如果會計是真正重要的,我會建議使用十進制類型,而不是雙。 Double會更快,但Decimal更精確。找出哪種權衡是合理的,並據此作出決定。 – Cory