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

如何修改DataGridView列值:将is_active为0的显示为ACTIVE

解决DataGridView中is_active列值为0时显示"ACTIVE"的问题

先给你指出现有代码的几个明显问题:

  • SQL语句里加了where is_active = 1,直接把is_active=0的行都过滤掉了,根本碰不到要处理的数据
  • 你写的dt.Columns(3).value完全不对,DataTable的列对象没有value属性,要改的是行里的单元格值,不是列本身
  • DataGridView1.Columns(3).ToString = 1这个判断逻辑离谱,Columns(3)是列对象,ToString出来的是列的类型名之类的内容,和1完全没法匹配

下面给你两种靠谱的实现方式,按需选择:

方式1:直接在SQL里处理(最简单)

直接让数据库返回你要显示的文本,绑定后不用额外操作:

Dim dt As DataTable
dt = exec("select 
            *, 
            CASE WHEN is_active = 0 THEN 'ACTIVE' ELSE CAST(is_active AS VARCHAR) END AS is_active_show 
          from tbl_credentials 
          where is_status = 2") ' 把is_active=1的过滤条件删掉,不然看不到目标行

DataGridView1.DataSource = dt
' 要是不想显示原始的is_active列,直接隐藏即可
DataGridView1.Columns("is_active").Visible = False

方式2:用DataGridView的CellFormatting事件(适合需要保留原始数值的场景)

如果之后还要用到is_active的原始数值,只是界面显示改文本,就用这个方法:

首先正常绑定数据(记得删掉SQL里的is_active=1过滤条件):

Dim dt As DataTable
dt = exec("select * from tbl_credentials where is_status = 2")
DataGridView1.DataSource = dt

然后给DataGridView添加CellFormatting事件处理:

Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    ' 先确认当前列是is_active列(用列名比索引靠谱,防止列顺序变动后出错)
    If DataGridView1.Columns(e.ColumnIndex).Name = "is_active" Then
        ' 检查单元格值是否为0
        If e.Value IsNot Nothing AndAlso Convert.ToInt32(e.Value) = 0 Then
            e.Value = "ACTIVE"
            e.FormattingApplied = True ' 标记已完成格式化,避免重复处理
        End If
    End If
End Sub

最后提醒一句:一定要把SQL里的is_active=1去掉,不然永远不会有is_active=0的行显示出来,逻辑等于白写。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:51:35