(在2021.4.29版本后,官方已经增加组合查询直转DataTable的方法,新版本用户不需要学习本帖子)
一、发现需求:
'用于给fxDataSource这种合并表转Json用的 'fxDataSource底层是Data.DataTable Dim dt As Data.DataTable = args(0) Dim jo As New JObject Dim ja As New JArray jo("list") =ja For i As Integer =0 To (dt.Rows.Count - 1) Dim jo2 As new JObject ja.Add(jo2) Dim dr As Data.DataRow = dt.Rows(i) Functions.Execute("fxRow2JObject",dr,jo2) Next Return jo2.fxRow2JObject
'用于给fxDataSource这种合并表转Json用的 Dim dr As Data.DataRow = args(0) Dim jo As JObject = args(1) Static dCols As new List(of String) dCols.Add("_Identify") dCols.Add("_Locked") dCols.Add("_SortKey") dCols.Add("System_Sort_Temporary") dCols.Add("System_Filter_Temporary") dCols.Add("System_Filter_Unique") Dim dcType As String Dim dcName As String For Each dc As Data.DataColumn In dr.Table.Columns dcType = dc.DataType.Name dcName = dc.ColumnName '把底层表没用的几列排除掉 If dCols.Contains(dcName) Then Continue For End If If dcType ="String" Then If dr.IsNull(dcName) Then jo(dcName) = "" Else jo(dcName) = CStr(dr(dcName)) End If Else If dcType ="Boolean" Then jo(dcName) = CBool(dr(dcName)) Else If dcType ="Int16" OrElse dcType ="Int32" OrElse dcType ="Byte" OrElse dcType ="Single" OrElse dcType ="Double" OrElse dcType ="Decimal" Then If dr.IsNull(dcName) Then jo(dcName) = 0 Else jo(dcName) = Val(dr(dcName)) End If Else If dcType ="DateTime" Then If dr.Isnull(dcName) =False Then jo(dcName) = CStr(dr(dcName)) Else jo(dcName) = "" End If End If Next
For Each dr As Data.DataRow In dt1.Rows dr("型号") = "aaa" Next
For Each dr As Data.DataRow In dt1.Rows //错误写法,会如下图报错,什么DBNull不支持运算符之类的 dr("退货总金额") = dr("退货数量") * dr("退货金额") //正确写法 dr("退货总金额") = Val(dr("退货数量").ToString) * Val(dr("退货金额").ToString) Next
If dt1.Columns.Contains("新列") =False Then dt1.Columns.Add("新列",Gettype(String)) End If可以添加的类型有以下
名称 | .net类型 | 对应狐表类型 |
字符串(常用) | System.String | String |
日期时间(常用) | System.DateTime | Date |
逻辑值(常用) | System.Boolean | Boolean |
微整数 | System.Byte | Byte |
短整数 | System.Int16 | Short |
整数(常用) | System.Int32 | Integer |
长整数 | System.Int64 | Long |
单精度小数 | System.Single | Single |
双精度小数 | System.Double | Double |
高精度小数(常用) | System.Decimal | Decimal |
If dt1.Columns.Contains("利润") =False Then dt1.Columns.Add("利润",Gettype(Decimal),"IsNull(销售_金额,0) - IsNull(进货_金额)") End If
Dim dr As Data.DataRow = dt.NewRow //第一步创建独立 行对象 dr("型号") = "aaa" dt.Rows.Add(dr) //第二步把 行对象 添加到 行集合 Output.show(dt.Rows.Count) //得到结果是1