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

将DataGridView绑定到List(Of String)显示长度而非内容的解决方法

解决DataGridView绑定List(Of String)显示字符串长度的问题

方法一:手动添加列并指定绑定属性

DataGridView自动生成列时,会反射String类型的公开属性,而String仅Length是公开属性,所以默认显示长度。可以关闭自动列生成,手动添加列并绑定空字符串,让控件直接显示字符串对象本身:

' 关闭自动生成列
DataGridView1.AutoGenerateColumns = False
' 创建并配置列
Dim contentColumn As New DataGridViewTextBoxColumn()
contentColumn.DataPropertyName = "" ' 关键设置,绑定空字符串会直接显示原对象
contentColumn.HeaderText = "字符串内容"
DataGridView1.Columns.Add(contentColumn)
' 绑定数据源
DataGridView1.DataSource = New List(Of String) From {"测试文本1", "测试文本2", "测试文本3"}

方法二:用自定义类包装字符串

把字符串放到带公开属性的自定义类中,这样DataGridView能识别并显示属性值,后续扩展也更灵活:

' 定义包装类
Public Class StringItem
    Public Property Content As String
End Class

' 转换列表并绑定
Dim originalList As New List(Of String) From {"测试文本1", "测试文本2", "测试文本3"}
Dim wrappedList = originalList.Select(Function(s) New StringItem With {.Content = s}).ToList()
DataGridView1.DataSource = wrappedList

方法三:利用CellFormatting事件修正显示

保留自动生成列,通过事件把显示的长度替换为原字符串:

' 绑定数据源
DataGridView1.DataSource = New List(Of String) From {"测试文本1", "测试文本2", "测试文本3"}

' 添加CellFormatting事件处理
AddHandler DataGridView1.CellFormatting, Sub(sender, e)
    If TypeOf e.Value Is Integer Then
        Dim sourceList = DirectCast(DataGridView1.DataSource, List(Of String))
        e.Value = sourceList(e.RowIndex)
        e.FormattingApplied = True ' 标记已完成格式化
    End If
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:52:52