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

VB.NET中DataTable表达式列只读问题及数据迁移报错求助

问题解决:Column 'C' is read-only

错误原因

列C是DataTable的表达式计算列(创建时通过第三个参数定义了计算逻辑),这类列的ReadOnly属性默认设为True,无法直接对其赋值,所以你尝试给newRow("C")赋值时触发了只读错误。

解决方案

表达式列会自动根据依赖列(此处为A、B)的值计算结果,因此不需要手动给C列赋值。只需移除赋值C列的代码,当你给新行的A、B列赋值后,C列会自动生成对应的值。

同时可以简化代码,无需提前统计选中行数,直接循环处理即可;另外添加跳过DataGridView自动生成空行的逻辑,避免无效处理。

修改后的完整代码

Public Class Form1
    Public dt As DataTable
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        dt = New DataTable
        dt.Columns.Add("A", GetType(String))
        dt.Columns.Add("B", GetType(String))
        dt.Columns.Add("C", GetType(String), "TRIM(IIF(A Is Null Or SUBSTRING(A, 1, 1) = '-', '', A) + IIF(B Is Null Or SUBSTRING(B, 1, 1) = '-', '', ' ' + B))")
        dt.Rows.Add("BALOTELLY", "OLD WARDAH (02)")
        dt.Rows.Add("TOYOBO FODU THOMPSON", "LIGHT BLACK (12)")
        dt.Rows.Add("MCR", "-")
        dt.Rows.Add("WALLY COTTON CREAP", "-")
        dt.Rows.Add("WALLY COTTON CREAP", "BLACK (23)")
        dt.Rows.Add("-", "-")
        DataGridView1.DataSource = dt
        Dim CheckedBoxColumn As New DataGridViewCheckBoxColumn
        CheckedBoxColumn.Width = 40
        CheckedBoxColumn.Name = "checkboxcolumn"
        CheckedBoxColumn.HeaderText = "Check"
        DataGridView1.Columns.Insert(0, CheckedBoxColumn)
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim selectedRows As DataTable = dt.Clone
        For Each row2 As DataGridViewRow In DataGridView1.Rows
            ' 跳过DataGridView自动生成的空行
            If row2.IsNewRow Then Continue For
            
            Dim isselect As Boolean = Convert.ToBoolean(row2.Cells("checkboxcolumn").Value)
            If isselect Then
                Dim newRow As DataRow = selectedRows.Rows.Add()
                newRow("A") = dt.Rows(row2.Index)("A")
                newRow("B") = dt.Rows(row2.Index)("B")
                ' 移除手动赋值C的代码,表达式会自动计算C的值
            End If
        Next row2
        DataGridView2.DataSource = selectedRows
        'theLabel.DataSource = selectedRows
    End Sub
End Class

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 01:17:27