CS-Script调用后DataTable丢失列与行的问题求助
问题分析:DataSet传递到CS-Script后复制DataTable丢失数据的问题
问题描述
C#应用调用CS-Script方法时,传入包含DataTable X的DataSet。脚本内新建DataTable Y并加入DataSet,调用DataTable.Copy()将X复制到Y,脚本内验证Y有6列约2000行,但返回C#程序后,Y仍存在却无列和行。其他修改DataSet中DataTable的脚本可正常返回结果,求问原因。
脚本代码
using System; using System.Data; using System.IO; using CSScript_Types; using System.Windows.Forms; using InSight; // This is the class that does the Real work of the CS Script After Query work public class AfterTableScripts : iAfterTableStuff { // This is the generic routine that is called from InSights Into Data // Return value is string so that we can handle Bool, string, number, etc. public CSScriptReturnValueClass AfterTableProcess(DataSet CurrDataSet, string CurrTableName, Form_InSightsMain MainForm) { CSScriptReturnValueClass ReturnRec = new CSScriptReturnValueClass(); try { // Here is the code to be run after the Table is created in the dataset DataTable QHRInvoices = CurrDataSet.Tables["QHRInvoices"]; DataTable DupTable = CurrDataSet.Tables.Add("DupsTable"); DupTable = QHRInvoices.Copy(); DupTable.TableName = "DupsTable"; // Now Setup the Return Value ReturnRec.Success = true; ReturnRec.ReturnValue = ""; ReturnRec.ErrorMsg = ""; } catch (Exception Ex) { // Now Setup the Return Value ReturnRec.Success = false; ReturnRec.ReturnValue = ""; ReturnRec.ErrorMsg = Ex.Message; } return ReturnRec; } }
C#调用代码
CSScriptReturnValueClass ReturnValue = new CSScriptReturnValueClass(); //string ReturnValue; dynamic AfterTableScript = CSScript.Evaluator.LoadCode(CurrCode); ReturnValue = AfterTableScript.AfterTableProcess(CurrDataSet, CurrTableName, MainForm); if (ReturnValue.Success) { return true; } else { // Need to Change this to a Logging routine FlexibleMessageBox.Show("Failure of CS Script: Error: " + ReturnValue.ErrorMsg, "CodeRunAfterQuery - Message"); return false; }
原因分析
核心问题出在**DataTable.Copy()的使用逻辑**和DataSet中DataTable的引用关系:
- 执行
DataTable DupTable = CurrDataSet.Tables.Add("DupsTable");时,已经在DataSet中创建了一个空的DataTable实例,DupTable此时指向这个实例。 - 随后执行
DupTable = QHRInvoices.Copy();,DupTable被重新赋值为Copy()返回的新DataTable实例——这个新实例并未被添加到DataSet中。 - 脚本内验证时,你检查的是这个新的
DupTable实例(有数据),但DataSet中实际存在的还是最初创建的空表。返回主程序后,主程序访问的是DataSet里的空表,自然看不到列和行。
解决方案
有两种可行的修正方式:
方式一:直接添加复制后的表到DataSet
去掉先创建空表的步骤,直接将Copy()的结果加入DataSet:
DataTable QHRInvoices = CurrDataSet.Tables["QHRInvoices"]; DataTable DupTable = QHRInvoices.Copy(); DupTable.TableName = "DupsTable"; CurrDataSet.Tables.Add(DupTable); // 直接添加带数据的表
方式二:填充已加入DataSet的空表
如果需要保留先创建表的逻辑,不要重新赋值,而是用Clone()复制结构后导入数据,或直接用Merge():
DataTable QHRInvoices = CurrDataSet.Tables["QHRInvoices"]; DataTable DupTable = CurrDataSet.Tables.Add("DupsTable"); // 复制表结构 DupTable = QHRInvoices.Clone(); // 导入所有行 foreach (DataRow row in QHRInvoices.Rows) { DupTable.ImportRow(row); } // 或用Merge更简洁 // DupTable.Merge(QHRInvoices);
内容的提问来源于stack exchange,提问作者G Bradley MacDonald
相关产品推荐
相关产品推荐

