我正在使用以下代码(基于devexpress
帮助论坛)阻止用户在48 characters
MemoEdit
行
Private Sub txtAuthors_EditValueChanging(sender As System.Object, e As DevExpress.XtraEditors.Controls.ChangingEventArgs) Handles txtAuthors.EditValueChanging
If e.NewValue Is Nothing Then
'No Value found in memoEditor
Return
End If
'Max lenght of textbox
Dim maxLength As Integer = 48
Dim edit As DevExpress.XtraEditors.MemoEdit = TryCast(sender, DevExpress.XtraEditors.MemoEdit)
For Each str As String In edit.Lines
If str.Length > maxLength Then
e.Cancel = True
Return
End If
Next str
End Sub
此函数可防止插入超过48个字符的String。但我真正希望实现的目标如下:
我的目标:
如果用户使用Ctrl + V/Paste
输入新字符串(使用more than 48 chars
)。它不应该阻止输入所有数据。控制应该除the first 48 chars
之外的其余部分。
如何实现这种行为。我试图操纵e.NewValue
,但无济于事......
关于Lines
- 属性:
You are not able to use the Lines property to change a particular array's element
directly. Instead, you should read the Lines property to get the array, change
the required array's element and then assign the array back to Lines.
注意:我读过这篇文章(Limit the input length of a DevExpress TextEdit and MemoEdit controls),但没有帮助
注2: MemoEdit内部的输入可能会有所不同,从普通用户输入(按任意键或Ctrl + V
)到来自WCF服务的基于计算机的输入
答案 0 :(得分:1)
使用标准的winform文本框可以通过处理KeyDown
事件,查找Ctrl + V
个密钥并查看Cliboard
文本来实现。
Private Sub txtAuthors_KeyDown(sender As Object, e As KeyEventArgs) Handles txtAuthors.KeyDown
If ((e.Modifiers = Keys.Control) AndAlso (e.KeyCode = Keys.V)) Then
Dim text As String = My.Computer.Clipboard.GetText()
If (text.Length > 48) Then
My.Computer.Clipboard.SetText(text.Substring(0, 48))
End If
End If
End Sub
注意:我没有安装devexpress,因此我无法保证这适用于MemoEdit
控件。
答案 1 :(得分:0)
经过一番试验&错误(添加了一些无限循环),我设法找到一个好的(不完美的)解决方案。我希望以下代码对任何人都有用。
Public Sub EditValueChanged(sender As System.Object, e As System.EventArgs) Handles txt.EditValueChanged
Dim edit As DevExpress.XtraEditors.MemoEdit = TryCast(sender, DevExpress.XtraEditors.MemoEdit)
'Take copy of the array
Dim myStringArrayCopy As String() = control.Lines
Dim hasEdits As Boolean = False
For Each str As String In myStringArrayCopy
If str.Length > maxCharCount Then
Dim indexString As Integer = Array.IndexOf(myStringArrayCopy, str)
myStringArrayCopy(indexString) = str.Substring(0, 47)
hasEdits = True
End If
Next str
If (hasEdits) Then
control.Lines = myStringArrayCopy
control.Refresh()
End If
End Sub
我对这段代码有几点评论。
备注1:使用EditValueChanged而不是EditValueChanging。在编辑后而不是在中间修改文本框更有意义。
备注2:如果使用超过48个字符进行了编辑。然后缩短字符串,但光标将放在第一行(这是一个多行txt)
备注3:不要忘记刷新()。否则,用户将无法看到正在进行的更改。