【问题标题】:Sentence case or proper case in a TextBox文本框中的句子大小写或正确大小写
【发布时间】:2026-02-23 12:35:01
【问题描述】:

我希望我的TextBox 将我输入的文本设为Sentence Case(ProperCase).. 但我不想在Lost FocusKeyPress 之类的事件中编写任何代码。

默认情况下,每当用户在文本框中输入或键入时,每个单词的第一个字母都应自动转换为UpperCase

【问题讨论】:

  • 我可能错了,但我认为唯一的方法是在使用事件输入文本时检查文本框的值并相应地更新文本。
  • 我已经尝试过使用 Culture Class,但我认为这对处理来说会很繁重..
  • 您正在处理用户输入。您有 1 亿个 cpu 周期来完成工作,然后用户才会注意到。
  • 感谢您提出这个问题 - 我投了赞成票,因为我不知道答案

标签: .net vb.net textbox


【解决方案1】:

我不知道如何在 WinForms 中执行此操作而不在事件中添加一些代码。 TextBox 的CharacterCasing 属性允许您强制输入的所有字符为大写或小写,但不能执行正确大小写。顺便说一句,只需一行代码即可在事件中执行此操作:

TextBox1.Text = StrConv(TextBox1.Text, VbStrConv.ProperCase)

用于跨多个文本框执行此操作的更通用的处理程序涉及将多个事件附加到同一代码:

'Attach multiple events to this handler
Private Sub MakeProperCase(sender As Object, e As EventArgs) Handles _
    TextBox1.LostFocus, TextBox2.LostFocus, TextBox3.LostFocus

    'Get the caller of the method and cast it to a generic textbox
    Dim currentTextBox As TextBox = DirectCast(sender, TextBox)
    'Set the text of the generic textbox to Proper Case
    currentTextBox.Text = StrConv(currentTextBox.Text, VbStrConv.ProperCase)

End Sub

在 ASP.NET 中,您可以这样做without code;有一个名为text-transform 的CSS 属性,该属性的值之一是capitalize。当应用于文本输入元素时,它将每个单词的首字母大写。

【讨论】:

    【解决方案2】:

    本例有两个控件:cboDestination 和txtUser。当您键入字母时,它会生成您想要的内容。

    Private Sub properCase_TextChanged(sender As Object, e As System.EventArgs) _ 
            Handles cboDestination.TextChanged, txtUser.TextChanged
            Dim n As Integer = sender.SelectionStart
            sender.Text = StrConv(sender.Text, VbStrConv.ProperCase)
            sender.SelectionStart = n
    End Sub
    

    【讨论】: