You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET TextBox光标位置插入字符串无选中文本时异常求助

TextBox光标位置插入字符串异常问题解决

问题原因分析

  1. 选中状态判断错误:用MyTextBox.SelectedText <> Nothing判断是否有选中内容是错误的。在VB.NET中,未选中任何文本时SelectedText返回**空字符串("")**而非Nothing,这个判断条件永远不会触发,导致后续逻辑出错。
  2. 错误清空内容:执行MyTextBox.SelectedText = Nothing会直接清空整个TextBox的文本,而非仅删除选中部分。正确删除选中内容的方式是设置SelectedText = ""。
  3. 变量类型未明确:int_index未声明为整数类型,可能导致SelectionStart的取值被隐式转换,引发光标位置识别错误。

修正后的代码

Dim str_Left, str_Right As String
Dim str_Insert As String = "Test string insert"
Dim int_index As Integer ' 明确声明为整数类型

' 判断是否有选中文本,有则清空选中内容
If Not String.IsNullOrEmpty(MyTextBox.SelectedText) Then
    MyTextBox.SelectedText = ""
End If

' 获取光标位置
int_index = MyTextBox.SelectionStart

' 拆分光标左右的文本
str_Left = MyTextBox.Text.Substring(0, int_index)
str_Right = MyTextBox.Text.Substring(int_index)

' 拼接并设置新文本
MyTextBox.Text = str_Left & str_Insert & str_Right

' 可选:插入后将光标定位到插入文本的末尾
MyTextBox.SelectionStart = int_index + str_Insert.Length

额外优化说明

  • 用.Substring()替代Mid():VB.NET中字符串的.Substring()方法比传统Mid()函数更直观,更符合.NET框架使用习惯。
  • 新增光标定位:插入完成后将光标移到插入文本末尾,提升用户体验。

内容的提问来源于stack exchange,提问作者Terabithia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:42:22