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

VB.NET中在DataGridView添加行并显示数据来源(famille1/famille2)

没问题,我来帮你搞定这个需求——用VB.NET在DataGridView里新增行,同时明确显示数据来源是famille1还是famille2。我把思路和完整代码都整理好了,保证清晰好懂。

实现思路
  • 首先得确保DataGridView有专门的列来显示数据来源,你可以在窗体设计界面直接拖列,也可以用代码动态创建
  • 准备好要添加的文章数据时,把对应的来源标识(famille1/famille2)一起带上
  • 调用DataGridView的Rows.Add()方法,把文章数据和来源信息一起填入新行里
代码示例(两种场景)

场景1:设计时已经建好列

如果你已经在窗体设计器里给DataGridView添加了文章标题、文章内容、数据来源这几列,直接用下面的代码就能加行:

' 模拟文章数据和来源,实际开发中可以替换成你的真实数据
Dim articleTitle As String = "VB.NET入门指南"
Dim articleContent As String = "这是一篇介绍VB.NET基础的文章"
Dim dataSource As String = "famille1" ' 这里可以根据实际来源切换成famille2

' 新增一行,把数据和来源一起填入
DataGridView1.Rows.Add(articleTitle, articleContent, dataSource)

场景2:动态创建列(适合初始无列的情况)

如果你的DataGridView一开始没有列,也可以用代码动态创建所有需要的列,包括数据来源列:

' 可以把这段列初始化代码放在Form_Load事件里
If DataGridView1.Columns.Count = 0 Then
    ' 创建文章标题列
    Dim titleCol As New DataGridViewTextBoxColumn()
    titleCol.HeaderText = "文章标题"
    titleCol.Name = "TitleCol"
    DataGridView1.Columns.Add(titleCol)

    ' 创建文章内容列
    Dim contentCol As New DataGridViewTextBoxColumn()
    contentCol.HeaderText = "文章内容"
    contentCol.Name = "ContentCol"
    DataGridView1.Columns.Add(contentCol)

    ' 创建数据来源列(重点)
    Dim sourceCol As New DataGridViewTextBoxColumn()
    sourceCol.HeaderText = "数据来源"
    sourceCol.Name = "SourceCol"
    sourceCol.ReadOnly = True ' 设置只读,防止用户修改来源信息
    DataGridView1.Columns.Add(sourceCol)
End If

' 准备真实数据和来源
Dim articleTitle As String = ".NET性能优化技巧"
Dim articleContent As String = "分享几个提升.NET应用性能的小技巧"
Dim dataSource As String = "famille2"

' 新增行
DataGridView1.Rows.Add(articleTitle, articleContent, dataSource)
额外优化提示

如果你想让来源信息更直观,可以给不同来源设置不同的样式,比如用颜色区分:

' 先在窗体的事件列表里绑定DataGridView的CellFormatting事件,然后写下面的逻辑
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    ' 判断当前单元格是否是数据来源列
    If e.ColumnIndex = DataGridView1.Columns("SourceCol").Index AndAlso e.Value IsNot Nothing Then
        Select Case e.Value.ToString()
            Case "famille1"
                e.CellStyle.ForeColor = Color.DarkBlue ' famille1用蓝色
            Case "famille2"
                e.CellStyle.ForeColor = Color.DarkGreen ' famille2用绿色
        End Select
    End If
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:19:52