我在文本框Leave event
上使用此代码将文本框的first Letter
设置为uppercase
,在表单上我有特定的文本框,我想要完成相同的功能,但是有吗任何方式,以便我不需要在每个文本框离开事件中编写相同的代码,我该怎么做
private void txtAdrs2A_Leave(object sender, EventArgs e)
{
if (txtAdrs2A.Text.Length >= 1)
txtAdrs2A.Text = txtAdrs2A.Text.Substring(0, 1).ToUpper() + txtAdrs2A.Text.Substring(1);
}
答案 0 :(得分:1)
使用sender
参数,而不是通过TextBox
指定Id
:
private void TextBox_Leave(object sender, EventArgs e)
{
var box = sender as TextBox;
if(box != null && box.Text.Length > 0)
box.Text = box.Text.Substring(0, 1).ToUpper() + box.Text.Substring(1);
}
答案 1 :(得分:1)
使用sender
private void text_Leave(object sender, EventArgs e)
{
TextBox text = (TextBox)sender;
if (text.Text.Length >= 1)
{
text.Text = text.Text.Substring(0, 1).ToUpper() + text.Text.Substring(1
}
}
然后遍历所有文本框以将事件分配给他们
foreach (TextBox t in this.Controls.OfType<TextBox>())
{
t.Leave += new EventHandler(text_Leave);
}