System.ArgumentException: 输入数组长度大于此表中的列数。

完整错误信息

System.ArgumentException: 输入数组长度大于此表中的列数。
在 System.Data.DataTable.NewRecordFromArray(Object[] value)
在 System.Data.DataRowCollection.Add(Object[] values)
在 \MainFrm.ImportDB_InsertRecord(OleDbTransaction dbtran, DataTable destTable, String insertCommand, DataRow dr_src, String pKColumnName, Int32& primaryKeyValue, FilterColumn filterColumn) 位置 J:\csProjects\Main.cs:行号 2636
在 \MainFrm.ImportDB_ImportTable(OleDbConnection con_src, OleDbTransaction dbtran, String tableName, FilterColumn filterColumn) 位置 J:\csProjects\Main.cs:行号 2573
在 \MainFrm.ImportDB_ImportContract(OleDbConnection con_src, OleDbTransaction dbtran, String ProjectID_src, Int32& impContract_exist, Int32& impContract_succe) 位置 J:\csProjects\Main.cs:行号 2519
在 \MainFrm.ImportDB_ImportProject(String srcDBFilePath) 位置 J:\csProjects\Main.cs:行号 2382

错误代码行

destTable.Rows.Add(dr_src.ItemArray);

destTable类型为:System.Data.DataTable
dr_src的类型为:System.Data.DataRow

错误原因

dr_src包含的列数大于destTable包含的列数。

解决方案

根据目标数据表的结构生成新行,然后逐个字段填充;

DataRow dr_new = destTable.NewRow();
foreach (DataColumn dc in destTable.Columns)
{
    if (dr_src.Table.Columns.Contains(dc.ColumnName))
    {
        dr_new[dc.ColumnName] = dr_src[dc.ColumnName];
    }
}
public void CreateFileAndUpload(JObject requestJson, bool isUploadFile) { try { string uploadFilePath = ""; // 生成上传结果文件 CreateUploadFileInfo(requestJson, out uploadFilePath); if (!isUploadFile) { return; } if (uploadFilePath.Trim() == string.Empty) { log.Error(string.Format("uploadFilePath is emmpty")); return; } // 执行上传 DirectoryInfo dir = new DirectoryInfo(uploadFilePath); FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //获取目录下(不包含子目录)的文件和子目录 string uploadResult = ""; string csvPath = ""; string[] zipPath = new string[] { }; List<DataTable> csvTable = Enumerable.Repeat<DataTable>(null, 4).ToList(); foreach (FileSystemInfo file in fileinfo) { if (file is DirectoryInfo) //判断是否文件夹 { continue; } // 是文件执行上传 string fullPath = file.FullName; if (file.FullName.Contains(".qdf.csv")) { csvTable[0]= (ConvertCsvToDataTable(fullPath)); // .qdf.csv转换DataTable } if(file.FullName.Contains("_R_tilt_corrected.csv")) { csvTable[1] = ConvertCsvToDataTable(fullPath); } if (file.FullName.Contains("_G_tilt_corrected.csv")) { csvTable[2] = ConvertCsvToDataTable(fullPath); } if (file.FullName.Contains("_B_tilt_corrected.csv")) { csvTable[3] = ConvertCsvToDataTable(fullPath); } if (file.FullName.Contains(".zip")) { zipPath = new[] { fullPath }; } } // post上传数据&文件 JObject UpLoadQdfAndZIPObject = new JObject(); string mesResult = MesRequestHelper.UploadQdfAndZIP(zipPath, csvPath, csvTable, SystemConfig.MachineID, Use.ToClient.ToString(), SystemConfig.OrderID, SystemConfig.model, ProcessCode_RockyP1.BBModule_MTF_Test.ToString()); log.Info(string.Format("UploadQdfAndZIP mes返回的消息:{0}", mesResult)); UpLoadQdfAndZIPObject = JObject.Parse(mesResult); bool status = false; string msg = ""; if (UpLoadQdfAndZIPObject.Property("status") != null) { status = UpLoadQdfAndZIPObject["status"].Value<bool>(); } if (UpLoadQdfAndZIPObject.Property("msg") != null) { msg = UpLoadQdfAndZIPObject["msg"].ToString(); } if(status) // 通知机台后台服务 { bool result = BackendService(); log.Info(string.Format("通知机台后台服务结果:{0}", result)); } } catch (Exception ex) { log.Error(string.Format("UploadTestResult result:{0}, failed:{1}", requestJson.ToString(), ex.Message)); } } 这个函数为啥会捕捉到输入数组长度大于此表中的列数
06-12
System.ArgumentException HResult=0x80070057 Message=Matrix dimensions must agree: 2x3. Source=MathNet.Numerics StackTrace: 在 MathNet.Numerics.LinearAlgebra.Double.Factorization.DenseQR.Create(DenseMatrix matrix, QRMethod method) 在 MathNet.Numerics.LinearAlgebra.Double.DenseMatrix.QR(QRMethod method) 在 MathNet.Numerics.LinearAlgebra.Matrix`1.Solve(Vector`1 input, Vector`1 result) 在 MathNet.Numerics.LinearAlgebra.Matrix`1.Solve(Vector`1 input) 在 Motion_YC.Help.ScottPlotExtension.<>c__DisplayClass5_0.<UpdatePlot>b__4() 在 E:\C#\6所\Motion YC\Motion YC\01Main\Motion YC\Help\ScottPlotExtension.cs 中: 第 136 行 在 System.Windows.Threading.Dispatcher.Invoke(Action callback, DispatcherPriority priority, CancellationToken cancellationToken, TimeSpan timeout) 在 System.Windows.Threading.Dispatcher.Invoke(Action callback) 在 Motion_YC.Help.ScottPlotExtension.UpdatePlot(WpfPlot plot, ObservableCollection`1 data) 在 E:\C#\6所\Motion YC\Motion YC\01Main\Motion YC\Help\ScottPlotExtension.cs 中: 第 84 行 在 Motion_YC.Help.ScottPlotExtension.<>c__DisplayClass3_0.<OnValuesChanged>b__1(Object s, NotifyCollectionChangedEventArgs args) 在 E:\C#\6所\Motion YC\Motion YC\01Main\Motion YC\Help\ScottPlotExtension.cs 中: 第 57 行 在 System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) 在 Motion_YC.Models.MainViewModel.ReadCsv(String filePath) 在 E:\C#\6所\Motion YC\Motion YC\01Main\Motion YC\ViewModels\MainViewModel.cs 中: 第 342 行 在 Motion_YC.Models.MainViewModel.<get_OperateCommand>b__79_0(Object obj) 在 E:\C#\6所\Motion YC\Motion YC\01Main\Motion YC\ViewModels\MainViewModel.cs 中: 第 194 行 在 Motion_YC.Help.CommandBase.Execute(Object parameter) 在 E:\C#\6所\Motion YC\Motion YC\01Main\Motion YC\Help\CommandBase.cs 中: 第 39 行 在 System.Windows.Controls.Button.OnClick() 在 System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) 在 System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) 在 System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) 在 System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent) 在 System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) 在 System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) 在 System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) 在 System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) 在 System.Windows.Input.InputManager.ProcessStagingArea() 在 System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) 在 System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) 在 System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 在 System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 在 MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 在 System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 在 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) 在 System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) 在 MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) 在 MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) 在 System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) 在 System.Windows.Application.RunDispatcher(Object ignore) 在 System.Windows.Application.RunInternal(Window window) 在 Motion_YC.App.Main() 这句报错var coefficients = A.Solve(b);
最新发布
10-12
using System; using System.Linq; class ClosedTraverseAdjustment { static void Main() { Console.WriteLine("闭合导线平差计算程序(完整修复版)"); Console.WriteLine("===================================="); // 输入控制点坐标 double x0 = ReadValue<double>("请输入起点X坐标(m): "); double y0 = ReadValue<double>("请输入起点Y坐标(m): "); // 输入导线参数 int n = ReadValue<int>("请输入导线边数: "); if (n < 3) { Console.WriteLine("错误:导线边数必须大于等于3!"); return; } // 输入各边观测数据 double[] lengths = ReadArray(n, "边长(m): ", ReadValue<double>); bool isLeftAngle = SelectAngleType(); double[] angles = ReadAngles(n, "观测角度(度分秒): ", isLeftAngle); // 输入起始方位角 double alpha0 = ReadAngle("请输入起始坐标方位角(度分秒 格式: 度 分 秒): "); // 角度闭合差计算 var angleClosure = CalculateAngleClosure(angles, n); Console.WriteLine($"\n角度闭合差: {angleClosure.closure * 3600:F4}″"); Console.WriteLine($"理论总角度: {angleClosure.theoretical:F2}°, 实际总角度: {angleClosure.total:F2}°"); // 角度改正 double[] correctedAngles = CorrectAngles(angles, angleClosure.closure); // 坐标方位角推算 double[] azimuths = CalculateAzimuths(alpha0, correctedAngles, isLeftAngle); // 坐标增量计算 var deltas = CalculateDeltas(lengths, azimuths); // 闭合差计算与分配 var closureErrors = CalculateClosureErrors(deltas.deltaX, deltas.deltaY); var adjustedDeltas = AdjustDeltas(deltas.deltaX, deltas.deltaY, closureErrors.fx, closureErrors.fy, lengths); // 坐标计算 var coordinates = CalculateCoordinates(x0, y0, adjustedDeltas.adjDeltaX, adjustedDeltas.adjDeltaY); // 结果输出 PrintResults(correctedAngles, azimuths, adjustedDeltas, coordinates, closureErrors.fx, closureErrors.fy); Console.WriteLine("\n计算完成!按任意键退出..."); Console.ReadKey(); } #region 输入处理模块 static T ReadValue<T>(string prompt) where T : IConvertible { while (true) { try { Console.Write(prompt); return (T)Convert.ChangeType(Console.ReadLine(), typeof(T)); } catch { Console.Write($"输入错误,请重新输入{prompt}"); } } } static T[] ReadArray<T>(int count, string basePrompt, Func<string, T> reader) { T[] array = new T[count]; for (int i = 0; i < count; i++) { string prompt = $"{basePrompt}{i + 1}: "; array[i] = reader(prompt); } return array; } static double[] ReadAngles(int count, string basePrompt, bool isLeftAngle) { Console.WriteLine($"\n当前设置为{(isLeftAngle ? "左角" : "右角")}观测模式"); return ReadArray(count, basePrompt, (prompt) => ReadAngle(prompt)); } static double ReadAngle(string prompt) { while (true) { try { Console.Write(prompt); string[] parts = Console.ReadLine().Split(' '); if (parts.Length != 3) throw new Exception("格式错误"); int deg = int.Parse(parts[0]); int min = int.Parse(parts[1]); double sec = double.Parse(parts[2]); if (deg < 0 || deg >= 360 || min < 0 || min >= 60 || sec < 0 || sec >= 60) throw new Exception("数值越界"); return deg + min / 60.0 + sec / 3600.0; } catch (Exception ex) { Console.WriteLine($"输入错误:{ex.Message}"); Console.WriteLine("请使用格式:度 分 秒(例如:123 30 45.5)"); } } } static bool SelectAngleType() { while (true) { Console.Write("请选择角度类型 (1-右角/2-左角): "); switch (Console.ReadLine()) { case "1": return false; case "2": return true; default: Console.WriteLine("输入错误,请重新选择!"); break; } } } #endregion #region 计算核心模块 static (double total, double theoretical, double closure) CalculateAngleClosure(double[] angles, int n) { double total = angles.Sum(); double theoretical = (n - 2) * 180; return (total, theoretical, total - theoretical); } static double[] CorrectAngles(double[] angles, double closure) { double correction = closure / angles.Length; for (int i = 0; i < angles.Length; i++) { angles[i] += correction; } return angles; } static double[] CalculateAzimuths(double startAzimuth, double[] angles, bool isLeftAngle) { double[] azimuths = new double[angles.Length]; azimuths[0] = startAzimuth; for (int i = 1; i < angles.Length; i++) { azimuths[i] = azimuths[i - 1] + (isLeftAngle ? 180 - angles[i - 1] : angles[i - 1] - 180); azimuths[i] %= 360; if (azimuths[i] < 0) azimuths[i] += 360; } return azimuths; } static (double[] deltaX, double[] deltaY) CalculateDeltas(double[] lengths, double[] azimuths) { double[] deltaX = new double[lengths.Length]; double[] deltaY = new double[lengths.Length]; for (int i = 0; i < lengths.Length; i++) { double rad = azimuths[i] * Math.PI / 180; deltaX[i] = lengths[i] * Math.Cos(rad); deltaY[i] = lengths[i] * Math.Sin(rad); } return (deltaX, deltaY); } static (double fx, double fy) CalculateClosureErrors(double[] deltaX, double[] deltaY) { if (deltaX.Length != deltaY.Length) throw new ArgumentException("输入数组长度不一致"); double sumX = deltaX.Sum(); double sumY = deltaY.Sum(); return (sumX, sumY); } static (double[] adjDeltaX, double[] adjDeltaY) AdjustDeltas(double[] deltaX, double[] deltaY, double fx, double fy, double[] lengths) { if (deltaX.Length != deltaY.Length || deltaX.Length != lengths.Length) throw new ArgumentException("输入数组长度不一致"); double totalLength = lengths.Sum(); double[] adjDeltaX = new double[deltaX.Length]; double[] adjDeltaY = new double[deltaY.Length]; for (int i = 0; i < deltaX.Length; i++) { adjDeltaX[i] = deltaX[i] - (fx * lengths[i] / totalLength); adjDeltaY[i] = deltaY[i] - (fy * lengths[i] / totalLength); } return (adjDeltaX, adjDeltaY); } static (double[] x, double[] y) CalculateCoordinates(double x0, double y0, double[] deltaX, double[] deltaY) { if (deltaX.Length != deltaY.Length) throw new ArgumentException("输入数组长度不一致"); double[] x = new double[deltaX.Length + 1]; double[] y = new double[deltaY.Length + 1]; x[0] = x0; y[0] = y0; for (int i = 0; i < deltaX.Length; i++) { x[i + 1] = x[i] + deltaX[i]; y[i + 1] = y[i] + deltaY[i]; } return (x, y); } #endregion #region 结果输出模块 static void PrintResults(double[] angles, double[] azimuths, (double[] adjDeltaX, double[] adjDeltaY) deltas, (double[] x, double[] y) coordinates, double fx, double fy) { Console.Clear(); Console.WriteLine("计算结果:"); Console.WriteLine("===================================="); Console.WriteLine($"角度闭合差: {fx * 3600:F4}″(X方向), {fy * 3600:F4}″(Y方向)"); Console.WriteLine($"坐标增量闭合差: fx={fx:F4}m, fy={fy:F4}m\n"); PrintTable("改正后角度", "边号", "角度(°)", angles); PrintTable("各边坐标方位角", "边号", "方位角(°)", azimuths); PrintTable("改正后坐标增量", "边号", "ΔX(m)", "ΔY(m)", deltas.adjDeltaX, deltas.adjDeltaY); PrintTable("各点坐标", "点号", "X(m)", "Y(m)", coordinates.x, coordinates.y); } static void PrintTable(string title, string col1, string col2, params double[][] data) { Console.WriteLine(title); Console.WriteLine($"{col1}\t{col2}\t" + string.Join("\t", data.Select((_, i) => $"列{i + 3}"))); for (int i = 0; i < data[0].Length; i++) { Console.WriteLine($"{i + 1}\t{data[0][i]:F4}\t" + string.Join("\t", data.Skip(1).Select(d => d[i].ToString("F4")))); } Console.WriteLine(); } #endregion }
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值