我想創建一個新的類繼承自System.Windows.Forms.TextBox並將keypress和keyup事件分配給我的控件。如何從文本框繼承並重寫keypress和keyup事件?
事情是這樣的:
class CurrencyTextbox : TextBox
{
private void CurrencyTextbox_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch != 8 && ch != 13)
{
e.Handled = true;
}
}
private void CurrencyTextbox_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(CurrencyTextbox.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
Int64 valueBefore = Int64.Parse(CurrencyTextbox.Text, System.Globalization.NumberStyles.AllowThousands);
CurrencyTextbox.Text = String.Format(culture, "{0:N0}", valueBefore);
CurrencyTextbox.Select(CurrencyTextbox.Text.Length, 0);
}
}
}
SLaks的答案作品增添一個普通的事件處理程序!非常感謝他。現在每次我想要它我需要從工具箱中拖動一個文本框到表單中,然後從from.Designer.cs中替換「private System.Windows.Forms.TextBox TextBox1;」到「私人CurrencyTextbox TextBox1;」。有沒有什麼方法可以將它添加到工具箱中,以便像其他控件一樣使用它。 – JatSing
我嘗試以數字格式返回貨幣文本框的文本。例如:textbox2.text = currencytextbox1.text(currencytextbox1.text = 999,999)然後我想textbox2.text = 999999(no「,」)。我試圖覆蓋文本獲取方法,但應用程序然後崩潰。你有什麼想法嗎?預先感謝 ! – JatSing