C# Error - Index (zero based) must be greater than or equal to zero

StringBuilder sb = new StringBuilder();
						
// Write file headers to String Builder
string[][] header = new string[][]
{
    	new string[] { "SampleID_C", "SampleType_c", "DateTested_c", "PartNum_c", "UseByDate_c", "TankNo_c", "PalleconNo_c", "SampleDesc_c", "TestBCER_c", "TestECOL_c", "TestENT_c", "TestLISTERIA_c", "TestTVC_c", "TestYM_c", "TestLEGIONELLA_c", "TestSALM_c", "TestSAUR_c", "OrgolepticAnalysisOK_c", "TestsRequired"},
};

Any ideas why this code is blowing up with this runtime error (compiles OK, but then thats expected I guess?)

Application Error

Exception caught in: mscorlib

Error Detail 
============
Message: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Program: CommonLanguageRuntimeLibrary
Method: AppendFormatHelper

Client Stack Trace 
==================
   at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.Format(String format, Object[] args)
   at Script.btnCreateCSV_Click(Object sender, EventArgs args)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at Infragistics.Win.Misc.UltraButtonBase.OnClick(EventArgs e)
   at Ice.Lib.Framework.EpiButton.OnClick(EventArgs e)
   at Infragistics.Win.Misc.UltraButton.OnMouseUp(MouseEventArgs e)
   at Ice.Lib.Framework.EpiButton.OnMouseUp(MouseEventArgs e)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

It’s a piece of code that I took from another working customisation and then just changed the column names. I can’t see a hard coded declaration of array size or anything, really not sure why it is unhappy!

As always, thanks for reading!

@josecgomez another chance to race @Chris_Conn to the answer… I appreciate the help this afternoon, I’m on holiday after tomorrow and need to get this working before I go. I think I’ve gone screen blind though, can’t understand why this simple line of code is blowing up. It’s a copy/paste from one that works!

I have to win in speed because Jose wins in all other categories :stuck_out_tongue:

The issue is going to be in your accessing of that multi-dimension array. Wheres the code for that?

Don’t think I have accessed it, all the code is commented out to troubleshoot and still get the error!

// **************************************************
// Custom code for MainController
// Created: 07/06/2018 09:59:18
// **************************************************
using System;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;
using Ice.BO;
using Ice.UI;
using Ice.Lib;
using Ice.Adapters;
using Ice.Lib.Customization;
using Ice.Lib.ExtendedProps;
using Ice.Lib.Framework;
using Ice.Lib.Searches;
using Ice.UI.FormFunctions;

using Ice.Lib.SharedUtilities.ImportExport;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Net;

public class Script
{
	// ** Wizard Insert Location - Do Not Remove 'Begin/End Wizard Added Module Level Variables' Comments! **
	// Begin Wizard Added Module Level Variables **

	// End Wizard Added Module Level Variables **

	// Add Custom Module Level Variables Here **

	public void InitializeCustomCode()
	{
		// ** Wizard Insert Location - Do not delete 'Begin/End Wizard Added Variable Initialization' lines **
		// Begin Wizard Added Variable Initialization

		// End Wizard Added Variable Initialization

		// Begin Wizard Added Custom Method Calls

		this.btnCreateCSV.Click += new System.EventHandler(this.btnCreateCSV_Click);
		// End Wizard Added Custom Method Calls
	}

	public void DestroyCustomCode()
	{
		// ** Wizard Insert Location - Do not delete 'Begin/End Wizard Added Object Disposal' lines **
		// Begin Wizard Added Object Disposal

		this.btnCreateCSV.Click -= new System.EventHandler(this.btnCreateCSV_Click);
		// End Wizard Added Object Disposal

		// Begin Custom Code Disposal

		// End Custom Code Disposal
	}

	private void MainController_Load(object sender, EventArgs args)
	{
		EpiDataView evContext = ((EpiDataView)(oTrans.EpiDataViews["CallContextClientData"])); 
		oTrans.EpiBaseForm.Text  = oTrans.EpiBaseForm.Text  + " (" + evContext.CurrentDataRow["CustomizationId"].ToString() + ")";
	}

	private void btnCreateCSV_Click(object sender, System.EventArgs args)
	{
		
		DialogResult dialogResult = MessageBox.Show("Are you sure you wish to proceed?\n\nCSV File will be created!", "Confirm File Upload", MessageBoxButtons.YesNo);
		
		if(dialogResult == DialogResult.Yes)
		{
		    
			EpiDataView edvSamples = (EpiDataView)oTrans.EpiDataViews["V_SampleListForExternalLab_1View"];
			
			//string fileName = "BVDairy_" + String.Format("{0:dd-MM-yyyy}", edvOrders.dataView[0]["BVD_LangCSV_CollectDate"]);
			string fileName = "BVDairy_" + String.Format("{0:dd-MM-yyyy}");
			string filePath = @"\\bvdairy.local\SharedFolders\Technical\SMS\SAMPLE REQUEST 2018\Outbound CSV Files\" + fileName + ".csv";   
			string delimiter = ","; 
			
			if (File.Exists(filePath)) 
		    {
		        EpiMessageBox.Show("File already exists, therefore orders already transmitted to SMS" + "\n" + "Please check!");
		    }
			else
			{	
				StringBuilder sb = new StringBuilder();
						
				// Write file headers to String Builder
				string[][] header = new string[][]
			    {
			    	new string[] { "SampleID_C", "SampleType_c", "DateTested_c", "PartNum_c", "UseByDate_c", "TankNo_c", "PalleconNo_c", "SampleDesc_c", "TestBCER_c", "TestECOL_c", "TestENT_c",
									"TestLISTERIA_c", "TestTVC_c", "TestYM_c", "TestLEGIONELLA_c", "TestSALM_c", "TestSAUR_c", "OrgolepticAnalysisOK_c", "TestsRequired"},
			    };
		
				/*int hdrLength;

				try
				{
					hdrLength = header.GetLength(0);
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.ToString());
				}*/
			    
				
				/*
				MessageBox.Show(hdrLength.ToString() + " length of hdr");

				for (int index = 0; index < hdrLength; index++)
			    	sb.AppendLine(string.Join(delimiter, header[index]));
		
				
				//Loop through all rows in grid, and append to String Builder
				int x = 0; 
				 
				for (x = 0; x <= edvSamples.dataView.Count - 1; x++ ) 
				{
					MessageBox.Show("inside for loop " + x);			
					string[][] output = new string[][]
		            {
		                new string[] { "\"" + edvSamples.dataView[x]["UD39_Key1"].ToString() + "\"", 
										"\"" + edvSamples.dataView[x]["UD39_SampleType_c"].ToString() + "\"",
										"\"" + String.Format("{0:dd/MM/yyyy}", edvSamples.dataView[x]["UD39_DateTested_c"]) + "\"",
										"\"" + edvSamples.dataView[x]["UD39_PartNum_c"].ToString() + "\"",
										"\"" + String.Format("{0:dd/MM/yyyy}", edvSamples.dataView[x]["UD39_UseByDate_c"]) + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TankNo_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_PalleconNo_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_SampleDesc_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TestBCER_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TestECOL_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TestENT_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TestLISTERIA_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TestTVC_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TestYM_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TestLEGIONELLA_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TestSALM_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_TestSAUR_c"].ToString() + "\"",
										"\"" + edvSamples.dataView[x]["UD39_OrgolepticAnalysisOK_c"].ToString() + "\"",										
										//"\"" + edvSamples.dataView[x]["UD39_"].ToString() + "\""},
										"\"" + "TestsRequired" + "\""},
		                
		            };
		            int length = output.GetLength(0);
		            
		            for (int index = 0; index < length; index++)
		                sb.AppendLine(string.Join(delimiter, output[index]));
				} 
				
				//Write contents of string builder to CSV
				File.WriteAllText(filePath, sb.ToString()); 
						
				EpiMessageBox.Show("File Upload Complete" + "\n" + "Ensure that email confirmation is received from Langdons!", "CSV File Uploaded");
				*/
			}
		}
		else
		{
		     MessageBox.Show("CSV creation cancelled!");
		}

	}

	
}

Should that comma after the closing bracket be there?

You got to be accessing it…with the string builder

Errror: StringBuilder.AppendFormatHelper

It’s this statement:

String.Format("{0:dd-MM-yyyy}");

“0” is an invalid placeholder – you need to add a parameter.

2 Likes

@erikj wins for actually looking at ALL the code

try this -
string fileName = string.Format(“BVDairy_{0}”,DateTime.Now.ToString(“dd-MM-yyyy”)) ;

Thank you! It seems I failed at a simple copy and paste from my other code! Looked at that bit and thought, oh I don’t need that on this one.