C#: cannot convert string to string [] [] - c#

I have a question regarding my code. The situation is the following: I am working with many arrays with data, all of same length. Then I want to build a second version with specific camps.
I have the following code:
string[][][] cuentasHFMPreFinal = new string[nroCuenta.Length][][];
string anoCubo = "'2019";
string escenarioCubo = "Control";
string versionCubo = "Version Vigente";
for (int i = 0, j = 0, k = 0; i < nroCuenta.Length && j < nroCuenta.Length && k < nroCuenta.Length; i++, j++, k++){
cuentasHFMPreFinal[i] = anoCubo;
}
The idea would be to give specific values to the new array (which will have more dimensions, this is a brief example). End array would end as something like:
cuentasHFM [anoCubo][escenarioCubo][versionCubo][....][lastVar]
The error is on the cuentasHFMPreFinal[i] = anoCubo part, giving the error on title.
Full code is:
static void Main(string[] args)
{
//-----------------------------------------------------------------------
//ARCHIVO CUENTAS AUTOMATICAS
//obtener direccion de archivo
string pathCuentasAuto = #"C:\DescargaHFM\data\cuentas_auto.txt";
pathCuentasAuto = Path.GetFullPath(pathCuentasAuto);
//leer lineas archivo y pasar a arreglo
string[] cuentasAuto = File.ReadAllLines(pathCuentasAuto);
//-----------------------------------------------------------------------
//ARCHIVO HFM CHILE
//obtener direccion de archivo
string pathHFM = #"C:\DescargaHFM\data\HFM.txt";
pathHFM = Path.GetFullPath(pathHFM);
//leer lineas archivo y pasar a arreglo
string[] hfm = File.ReadAllLines(pathHFM);
//obtener separador tab
string separadorTab = "\t";
//separar lineas por separadores
string[][] camposHFM = new string[hfm.Length][];
for (int i = 0; i < hfm.Length; i++) {
camposHFM[i] = hfm[i].Split(separadorTab.ToCharArray());
}
//arreglo con periodo(meses)
string[] mesesHFM = new string[camposHFM.Length];
for (int i = 0; i < camposHFM.Length; i++)
{
string mesPeriodo = camposHFM[i][0];
switch (mesPeriodo){
case "Per01":
mesPeriodo = "Jan";
break;
case "Per02":
mesPeriodo = "Feb";
break;
case "Per03":
mesPeriodo = "Mar";
break;
case "Per04":
mesPeriodo = "Apr";
break;
case "Per05":
mesPeriodo = "May";
break;
case "Per06":
mesPeriodo = "Jun";
break;
case "Per07":
mesPeriodo = "Jul";
break;
case "Per08":
mesPeriodo = "Aug";
break;
case "Per09":
mesPeriodo = "Sep";
break;
case "Per10":
mesPeriodo = "Oct";
break;
case "Per11":
mesPeriodo = "Nov";
break;
case "Per12":
mesPeriodo = "Dec";
break;
}
mesesHFM[i] = mesPeriodo;
}
//otener cantidad total y cantidad gl
double[] QTotalUSGAP = new double[hfm.Length];
double[] QTotalGL = new double[hfm.Length];
double[] QTotalResta = new double[hfm.Length];
for (int i = 0; i < camposHFM.Length; i++) {
QTotalUSGAP[i] = Double.Parse(camposHFM[i][3]);
QTotalGL[i] = Double.Parse(camposHFM[i][4]);
QTotalResta[i] = QTotalUSGAP[i] - QTotalGL[i];
}
//obtener numero cuenta
string[] nroCuenta = new string[hfm.Length];
/*Formula Excel:
*SI(IZQUIERDA(C2;4)="ACCT";MED(C2;5;LARGO(C2)-3);IZQUIERDA(C2;ENCONTRAR("_";C2)-1))
*/
for (int i = 0; i < camposHFM.Length; i++) {
nroCuenta[i] = camposHFM[i][2];
if (nroCuenta[i].Substring(0, 4) == "ACCT") {
nroCuenta[i] = nroCuenta[i].Substring(5, (nroCuenta[i].Length - 3));
}
else {
//int indexFind = nroCuenta[i].IndexOf('_');
//nroCuenta[i] = nroCuenta[i].Substring(0, (indexFind - 1));
nroCuenta[i] = nroCuenta[i].Substring(0, nroCuenta[i].Length);
}
}
//comprobar existencia de nroCuenta en cuentasAuto
string[] existeNroCuenta = new string[nroCuenta.Length];
for (int i = 0; i < nroCuenta.Length; i++){
if (cuentasAuto.Contains(nroCuenta[i])){
existeNroCuenta[i] = "TRUE";
}
else{
existeNroCuenta[i] = "FALSE";
}
}
//armar arreglo pre final
string[][][] cuentasHFMPreFinal = new string[nroCuenta.Length][][];
string anoCubo = "'2019";
string escenarioCubo = "Control";
string versionCubo = "Version Vigente";
string monedaCubo = "CLP";
string ubgCubo = "Generico UBG";
string ajusteICCubo = "Ajuste 99";
string organizacionCubo = "Generico";
for (int i = 0, j = 0, k = 0; i < nroCuenta.Length && j < nroCuenta.Length && k < nroCuenta.Length; i++, j++, k++){
cuentasHFMPreFinal[i] = anoCubo;
}
}

Use classes, structs or tuples to achieve what you're trying to achieve.

Related

My WindowsForm just ignore some code lines and I don't know why?

I've been programming a soft on VS in C#. It is an old program made by someone else by me but my problem is in my code I think. In this soft, there is two Form, the 1st one get some datas, and the second make the operations and also provide a report of the datas that I use.
double sum = 0;
for (int k = 0; k <= length - 1; )
{
sum += Convert.ToDouble(pisteA[k]);
k += 1;
}
double average = sum / 3;
I have an array containing Text and null values in the 2nd Form. I just want to make an average of this array, so with a for loop, I did what I have to do. But, when I launch my soft, It doesn't go through the line code and stops at this line.
sum += Convert.ToDouble(pisteA[k]);
When I use the Breakpoint to see what's happening, the code go through this line, and then go to my other form to execute this :
formImpression.Show();
To test something, I added a MessageBox.Show just after the line of the sum, and also before, and it seems that the soft execute the code above the problem line, but not the ones that are after this.
I seriously don't have any idea of what's happening.
Edit : For more comprehension about the code I use, I leave it here.
String[] varGen = { formulaire.Form1.varG.piste1, formulaire.Form1.varG.piste2, formulaire.Form1.varG.piste3, formulaire.Form1.varG.piste4, formulaire.Form1.varG.modulesPiste1, formulaire.Form1.varG.modulesPiste2, formulaire.Form1.varG.modulesPiste3, formulaire.Form1.varG.modulesPiste4 };
TextBox[] pisteA = { mesure1, mesure2, mesure3, mesure4, mesure5, mesure6, moyenne1 };
TextBox[] pisteB = { mesure7, mesure8, mesure9, mesure10, mesure11, mesure12, moyenne2 };
TextBox[] pisteC = { mesure13, mesure14, mesure15, mesure16, mesure17, mesure18, moyenne3 };
TextBox[] pisteD = { mesure19, mesure20, mesure21, mesure22, mesure23, mesure24, moyenne4 };
double moyenne = 0;
int indexMesures = 0;
bool presencepn = false;
for (int n = 0; n < dataGridView1.Rows.Count; n++)
{
if (formulaire.Form1.varG.pn == dataGridView1.Rows[n].Cells[0].Value.ToString() & formulaire.Form1.varG.pn != null)
{
presencepn = true;
//Initialisation
object module_A1 = dataGridView1.Rows[n].Cells[1].Value;
object module_A2 = dataGridView1.Rows[n + 1].Cells[1].Value;
object module_A3 = dataGridView1.Rows[n + 2].Cells[1].Value;
object module_D1 = dataGridView1.Rows[n].Cells[2].Value;
object module_D2 = dataGridView1.Rows[n + 1].Cells[2].Value;
object module_D3 = dataGridView1.Rows[n + 2].Cells[2].Value;
int moduleA1 = int.Parse(module_A1.ToString())-1;
int moduleA2 = int.Parse(module_A2.ToString())-1;
int moduleA3 = int.Parse(module_A3.ToString())-1;
int moduleD1 = int.Parse(module_D1.ToString())-1;
int moduleD2 = int.Parse(module_D2.ToString())-1;
int moduleD3 = int.Parse(module_D3.ToString())-1;
//Remplissage tableau sans exclusion
// Piste [1,2,3,4]
for (int j = 0; j < formulaire.Form1.varG.nbPistes; j++)
{
// Initialisation de la moyenne
moyenne = 0;
// Valeur pour la piste J
for (int i = 0; i < Convert.ToInt32(varGen[j + 4]); i++)
{
// Calcul de la moyenne
moyenne = moyenne + mesures[indexMesures];
// Choix de la piste
if (varGen[j] == "A")
{
pisteA[i].Text = Math.Round(mesures[indexMesures], 3).ToString(); // Remplissage des mesures
}
else if (varGen[j] == "B")
{
pisteB[i].Text = Math.Round(mesures[indexMesures], 3).ToString(); // Remplissage des mesures
pisteB[6].Text = Math.Round((moyenne / Convert.ToDouble(varGen[j + 4])), 3).ToString(); // Remplissage de la case moyenne
}
else if (varGen[j] == "C")
{
pisteC[i].Text = Math.Round(mesures[indexMesures], 3).ToString(); // Remplissage des mesures
pisteC[6].Text = Math.Round((moyenne / Convert.ToDouble(varGen[j + 4])), 3).ToString(); // Remplissage de la case moyenne
}
else if (varGen[j] == "D")
{
pisteD[i].Text = Math.Round(mesures[indexMesures], 3).ToString(); // Remplissage des mesures
pisteD[6].Text = Math.Round(moyenne / Convert.ToDouble(varGen[j + 4]), 3).ToString(); // Remplissage de la case moyenne
}
// Incrémentation de l'index des mesures
indexMesures += 1;
}
}
int length = pisteA.Length - 1;
//Suppression des modules exclus
for (int k = 0; k <= length; k++)
{
if (k == (moduleA1) | k == (moduleA2) | k == (moduleA3))
{
pisteA[k].Text = null;
}
}
for (int k = 0; k <= length; k++)
{
if (k == (moduleD1) | k == (moduleD2) | k == (moduleD3))
{
pisteD[k].Text = null;
}
}
double sum = 0;
for (int k = 0; k <= length - 1; )
{
sum += Convert.ToDouble(pisteA[k]);
k += 1;
}
double moyA = sum / 3;
pisteA[6].Text = Math.Round(moyA).ToString();
}
Have you this setting checked to see exception ?

Fill and 2D array from .txt file

So, I need to look through the file and fill and 2d array with data from the file. I couldn't figure any better way to do that than this, but this code just completly freezes. Here's the code.
The idea is that I'm gonna look through all of the text in a source file, then I'm gonna check if a line contains something I need and, if so, I will make additions to my 2D array, that I will then write to a different txt file.
string[,] FileBase = new string[100,100];
DateTime Date = DateTime.UtcNow;
string time = Date.ToString();
time = time.Replace(':', '.');
string ReportPath = Directory.GetCurrentDirectory() + "\\Report from " + time + ".txt";
int Value = 0;
int i = 0, j = 0;
string item;
int controlD = 0;
int sensor = 0;
int p = 0;
bool loadcell = false;
bool possensor = false;
int smth = 0;
string curr = comboBox1.SelectedItem.ToString();
curr = curr.Remove(0, curr.IndexOf("RCU") + 3);
int current = Convert.ToInt32(curr);
string localpath = path + "\\control\\RCU" + curr + "\\cfg\\RCU" + curr + ".cfg";
FileStream file1 = new FileStream(localpath, FileMode.Open);
StreamReader reader = new StreamReader(file1);
while ((item = reader.ReadLine()) != null)
{
for (i = p; i < 100; i++)
{
for (j = 0; j < 1000; i++)
{
if (item.Contains("Signal_Sensor"))
{
sensor++;
FileBase[i, j] = "Signal_SensorA" + sensor;
break;
}
else if (item.Contains("Signal_PositionA"))
{
controlD++;
FileBase[i, j] = "Signal_PositionA" + controlD;
break;
}
else if (item.Contains("Division") && (controlD != 0))
{
FileBase[i, j] = "Division";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("LowerLimitExternal"))
{
FileBase[i, j] = "LowerLimitExternal";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("UpperLimitExternal"))
{
FileBase[i, j] = "UpperLimitExternal";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("LowerLimit"))
{
FileBase[i, j] = "LowerLimit";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("UpperLimit"))
{
FileBase[i, j] = "UpperLimit";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("LoadCell"))
{
loadcell = true;
break;
}
else if (item.Contains("PositionSensor"))
{
possensor = true;
break;
}
else if (item.Contains("EnableSensorA" + smth))
{
smth++;
FileBase[i, j] = "EnableSensorA" + smth;
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("InvertSensorA"))
{
smth++;
FileBase[i, j] = "InvertSensorA" + (smth - 3);
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
if (smth ==6)
{
smth = 0;
break;
}
}
p = i;
break;
}
}
reader.Close();
File.Create(ReportPath);
FileStream ReportFill = new FileStream(ReportPath, FileMode.Open);
StreamReader reader1 = new StreamReader(ReportFill);
WriteArray();
reader1.Close();
Thanks in advance!

Visual studio C# Invisible Friend Game code

I've been trying how to make the couples, what I have to do is develop a program(console app) where I have to
Add players(max 30)
Mix those players between then(every name has to appear in each column once
For example:
The partner of Maria is Juan, therefore Maria has to give the gift to Juan, each person has to appear once on each side. I've tried 2 codes:
Code 1:
Console.WriteLine("Bienvenido al juego del amigo invisible!");
string[] nombres= new string[30];
bool salir = false;
int personas=30 ;
int cant = 1;
while (salir != true)
{
int opc;
Console.WriteLine("1-Introducir parejas 2-Amigo invisible 3-Introducir parejas 4- Añadir más personas 5-Salir ");
while (!int.TryParse(Console.ReadLine(), out opc))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
switch (opc)
{
case 1:
Nombres(ref nombres, ref personas);
break;
case 2:
Parejas(nombres,ref personas);
break;
case 3:
Parejitas(cant);
break;
case 4:
MasParejas(ref personas);
break;
case 5:
salir = true;
break;
}
}
static void Nombres(ref string[] nombres, ref int personas)
{
Console.WriteLine("Cuantas personas sois");
while (!int.TryParse(Console.ReadLine(), out personas))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
nombres = new string[personas];
Console.WriteLine("introduzca" + personas + "nombres");
for (int a = 0; a < personas; ++a)
{
nombres[a] = Console.ReadLine();
}
for (int a = 0; a >= personas;)
{
Console.WriteLine("Las personas que jugaran contigo serán:" + nombres[a]);
}
Console.Clear();
}
static void Parejas(string[] nombres, ref int personas)
{
Random rnd = new Random();
bool aprobado = false;
int[] usados = new int[personas];
Console.WriteLine("Hagamos las parjeas");
foreach (string persons in nombres)
{
do
{
for (int i = 0; i < personas; i++)
{
int h = rnd.Next(0, personas - 1);
do
{
string name = nombres[h];
if (name != null)
{
if (persons?.CompareTo(name) != 0 && usados.Contains(h))
{
aprobado = true;
Console.WriteLine($"{nombres[i]} va con {nombres[h]}");
}
}
usados[i] = h;
} while ( usados.Contains(h));
}
} while (!aprobado);
}
}
static void Parejitas(int cant)
{
Console.WriteLine("Hagamos las parejas por separado.");
string[] parejitas = new string[cant];
do
{
if (cant % 2 != 0)
{
while (!int.TryParse(Console.ReadLine(), out cant))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
}
} while (cant % 2 != 0);
Console.WriteLine("Introduzca los nombres de las parejas");
for (int i = 0; i < cant; i++)
{
parejitas[i] = Console.ReadLine();
}
for (int i = 0; i < cant; i++)
{
Console.WriteLine($"las parejas son {parejitas[i]} con {parejitas[i + 1]}");
}
Console.Clear();
}
static void MasParejas(ref int personas)
{
int más;
Console.WriteLine("¿Cuanta gente quiere añadir?");
while (!int.TryParse(Console.ReadLine(), out más))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
int total = personas + más;
do
{
if (total >= 30 || más % 2 != 0)
{
Console.WriteLine("Ha superado el limite de personas o introducido un número inpar, el limite es 30");
while (!int.TryParse(Console.ReadLine(), out más))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
}
} while (total >= 30 || más % 2 != 0);
int a = 1;
string[] personasañadidas = new string[más];
Console.WriteLine("Introduzca los nombres de los nuevos");
for (int i = 0; i < más; i++)
{
personasañadidas[i] = Console.ReadLine();
}
for (int j = 0;j < personasañadidas.Length; j++)
{
if (j< personasañadidas.Length-1)
{
Console.WriteLine($" Parejas: {personasañadidas[j]} con {personasañadidas[j + 1]}");
}
if (j==personasañadidas.Length-1)
{
Console.WriteLine($" Parejas: {personasañadidas[j]} con {personasañadidas[0]}");
}
}
}
Code 2:
static void Main(string[] args)
{
bool salir = false;
int cantidadPersonas=30 ;
string[] Personas = new string[cantidadPersonas];
while (salir != true)
{
int opc;
Console.WriteLine("1-Introducir parejas 2-Amigo invisible 3-Salir ");
while (!int.TryParse(Console.ReadLine(), out opc))
{
Console.Write("Valor incorrecto, inserta de nuevo: ");
}
switch (opc)
{
case 1:
MeterNombres(ref cantidadPersonas, ref Personas);
break;
case 2:
GenerarParejas(cantidadPersonas, Personas);
break;
case 3:
salir = true;
break;
}
}
static void MeterNombres(ref int cantidadPersonas, ref string[] Personas) {
Console.WriteLine("¿Cuantos sois?");
cantidadPersonas = Convert.ToInt32(Console.ReadLine());
do
{
if (cantidadPersonas % 2 != 0)
{
cantidadPersonas = Convert.ToInt32(Console.ReadLine());
}
} while (cantidadPersonas % 2 != 0);
Console.WriteLine("Introduzca los nombres de las personas que vayan a participar:");
for (int i = 0; i < cantidadPersonas; i++)
{
Personas[i]= Console.ReadLine();
}
Console.Clear();
Console.WriteLine("Los participantes son:");
for (int i = 0; i < cantidadPersonas; i++)
{
Console.WriteLine(Personas[i]);
}
}
static void GenerarParejas(int cantidadPersonas, string[] Personas)
{
Console.WriteLine("Comencemos a generar las parejas...");
string[] PersonasCopia = new string[cantidadPersonas];
Random rnd = new Random();
bool Repeticiones = false;
int NumeroAleatorio;
for (int i = 0; i < cantidadPersonas; i++)
{
PersonasCopia[i] = Personas[i];
}
for (int i = 0; i < cantidadPersonas; i++)
{
do
{
Repeticiones = false;
NumeroAleatorio = rnd.Next(0, cantidadPersonas);
if (Personas[i] == PersonasCopia[i])
{
Repeticiones = true;
}
} while (Repeticiones = false); ;
}
}

NPOI Excel Format not working

I have a function that is generating an Excel file using the NPOI Library. Witch for the most part is working fine just got a problem with style's they seem to function dodgy. Currently my focus is the number formats:
I would like all decimals to display as: 12.156.235,33 for example
According to the reserach on google the format that should do that should be: "#,##0.00" but the value shows up as: 12156235,33 and the cell type is set to general instead of number
It also looks like alot of people have problems with this. Hope there is a solution cos everything else I whanted to do I managed with the NPOI library and would not whant to switch now.
The procedure:
IDataFormat dataFormat;
public string GenerateExcel(ExcelData data)
{
var dateFormat = dataFormat.GetFormat("dd.MM.yyyy HH:mm:ss");
var decimalFormat = dataFormat.GetFormat("#,##0.00");
string xlsPath, xlsFile, xlsName;
xlsPath = Environment.GetEnvironmentVariable("TEMP");
xlsName = Path.GetRandomFileName().Replace(".", ""); //DateTime.Now.ToString("yyyy-MM-dd");
xlsName += ".xlsx";
xlsFile = Path.Combine(xlsPath, xlsName);
if (File.Exists(xlsFile))
File.Delete(xlsFile);
workbook = new XSSFWorkbook();
dataFormat = workbook.CreateDataFormat();
XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
NPOI.SS.UserModel.ICell cell;
Dictionary<int, int> maxColSize = new Dictionary<int, int>();
string title;
int rr;
foreach (var sheet in data.Sheets)
{
maxColSize.Clear();
if(sheet.Hidden != null)
foreach (var h in sheet.Hidden)
{
sheet.HideRow(h);
}
worksheet = (XSSFSheet)workbook.CreateSheet(sheet.Title);
rr = 0;
if (sheet.Titles!=null && sheet.Titles.Length > 0)
{
worksheet.CreateRow(rr);
rr++;
for (int t = 0; t < sheet.Titles.Length; t++)
{
title = (string)sheet.Titles[t].Title;
maxColSize.Add(t, title.Length);
cell = worksheet.GetRow(0).CreateCell(t, NPOI.SS.UserModel.CellType.String);
cell.SetCellValue(title);
if (sheet.Titles[t].Style != null)
cell.CellStyle = GetCellStyle(sheet.Titles[t].Style);
}
}
int cols = 0;
int cc = 0;
IRow row = null;
for (int r = 0; r < sheet.Rows.Length; r++)
{
if (sheet.Rows[r].row > -1)
{
rr = sheet.Rows[r].row;
row = worksheet.GetRow(sheet.Rows[r].row);
}
else
{
//rr = r;
row = worksheet.GetRow(rr);
}
if (row == null)
{
row = worksheet.CreateRow(rr);
}
if(sheet.Rows[r].Cells.Length > cols)
cols = sheet.Rows[r].Cells.Length;
for (int c = 0; c < sheet.Rows[r].Cells.Length;c++ )
{
cc = c;
if (sheet.Rows[r].Cells[c].column > -1)
{
cc = sheet.Rows[r].Cells[c].column;
}
if (!maxColSize.Keys.Contains(cc))
maxColSize.Add(cc, 0);
switch (sheet.Rows[r].Cells[c].DataType)
{
case "DateTime":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Numeric);
cell.SetCellValue((DateTime)sheet.Rows[r].Cells[c].Value);
cell.CellStyle.DataFormat = dateFormat;
if (maxColSize[cc] < cell.NumericCellValue.ToString().Length)
maxColSize[cc] = cell.NumericCellValue.ToString().Length;
break;
case "Numeric":
case "Decimal":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Numeric);
cell.SetCellValue(Convert.ToDouble(sheet.Rows[r].Cells[c].Value)); //sheet.Rows[r].Cells[c].Value
cell.CellStyle.DataFormat = decimalFormat;
if (maxColSize[cc] < cell.NumericCellValue.ToString().Length)
maxColSize[cc] = cell.NumericCellValue.ToString().Length;
break;
case "Integer":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Numeric);
cell.SetCellValue(Convert.ToInt32(sheet.Rows[r].Cells[c].Value));
cell.CellStyle.DataFormat = dataFormat.GetFormat("0");
if (maxColSize[cc] < cell.NumericCellValue.ToString().Length)
maxColSize[cc] = cell.NumericCellValue.ToString().Length;
break;
case "Date":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Numeric);
cell.SetCellValue((DateTime)sheet.Rows[r].Cells[c].Value);
cell.CellStyle.DataFormat = dataFormat.GetFormat("dd.MM.yyyy");
if (maxColSize[cc] < cell.NumericCellValue.ToString().Length)
maxColSize[cc] = cell.NumericCellValue.ToString().Length;
break;
case "Boolean":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Boolean);
cell.SetCellValue(Convert.ToBoolean(sheet.Rows[r].Cells[c].Value));
if (maxColSize[cc] < cell.BooleanCellValue.ToString().Length)
maxColSize[cc] = cell.StringCellValue.ToString().Length;
break;
case "Formula":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Formula);
cell.SetCellFormula((string)(sheet.Rows[r].Cells[c].Value));
if (maxColSize[cc] < cell.BooleanCellValue.ToString().Length)
maxColSize[cc] = cell.StringCellValue.ToString().Length;
break;
default:
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.String);
cell.SetCellValue((string)sheet.Rows[r].Cells[c].Value);
if (maxColSize[cc] < cell.StringCellValue.Length)
maxColSize[cc] = cell.StringCellValue.Length;
break;
}
if (sheet.Rows[r].Cells[c].Style != null)
{
var st = GetCellStyle(sheet.Rows[r].Cells[c].Style);
cell.CellStyle = st;
}
}
if (sheet.Rows[r].row == -1)
rr++;
if(sheet.Merge != null)
foreach (var merge in sheet.Merge)
{
worksheet.AddMergedRegion( new NPOI.SS.Util.CellRangeAddress(merge.FirstRow,merge.LastRow, merge.FirstColumn, merge.LastColumn));
}
}
foreach (var col in maxColSize)
{
worksheet.SetColumnWidth(col.Key, ((int)(col.Value * 1.14388)) * 256);
}
XSSFFormulaEvaluator.EvaluateAllFormulaCells(workbook);
}
using (var fs = new FileStream(xlsFile, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
return xlsFile;
}

After changing tabpage, the combobox crashes

I have a combobox outside my tabcontrol. In each tab control there is a datagridview full of values. In the combobox you can choose a conversion for all values. For example eV→meV.
When i am in the first tab and use the combobox there are no problems, but after i switch the tab and then wanna use the combobox the program list down however the whole combobox is full of try/catch
private void OpenB_Click(object sender, EventArgs e)
{
string[] result = new string[2];
bool lesen = false;
int Spalte = 0;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//Datagridview will be rested, so all values and rows are removed
for (int i = 1; i < Anzahl; i++)
{
DGV[i].Rows.Clear();
}
Anzahl = openFileDialog1.FileNames.Length;
counter = new int[Anzahl];
try
{
if (tabControl1.TabCount < Anzahl)
{
for (int i = 1; i <= Anzahl; i++)
{
if (i > tabControl1.TabCount)
{
string title = "Tab " + (tabControl1.TabCount + 1).ToString();
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
DataGridView NewDGV = new DataGridView();
NewDGV.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
NewDGV.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
NewDGV.Columns.Add("Energy", "Energy");
NewDGV.Columns[0].ReadOnly = true;
NewDGV.Columns.Add("Count Rate", "Count Rate");
NewDGV.Columns[1].ReadOnly = true;
NewDGV.Location = new System.Drawing.Point(3, 3);
NewDGV.Name = "NewDGV" + Convert.ToString(i);
NewDGV.RowHeadersVisible = false;
NewDGV.Size = new System.Drawing.Size(276, 379);
NewDGV.TabIndex = i;
foreach (DataGridViewColumn col in NewDGV.Columns)
col.SortMode = DataGridViewColumnSortMode.NotSortable;
NewDGV.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
DGV.Add(NewDGV);
tabControl1.TabPages[i - 1].Controls.Add(NewDGV);
}
}
}
else if (tabControl1.TabCount > Anzahl)
{
for (int i = tabControl1.TabCount - 1; i >= Anzahl; i--)
{
tabControl1.TabPages.Remove(tabControl1.TabPages[i]);
}
}
}
catch { }
try
{
//Double arrays and Datagridview will be attuned to the count of data
eV = new double[openFileDialog1.FileNames.Length][];
meV = new double[openFileDialog1.FileNames.Length][];
cm = new double[openFileDialog1.FileNames.Length][];
CR = new double[openFileDialog1.FileNames.Length][];
CRmax = new double[openFileDialog1.FileNames.Length][];
for (int i = 0; i < Anzahl; i++)
{
//Naming the columns after data names
string[] Dateiname = openFileDialog1.FileNames[i].Split('\\');
int L = Dateiname.Length;
tabControl1.TabPages[i].Text = Dateiname[L-1];
}
}
catch
{
}
//Datafiles will be read one by one
DataRead(result, ref lesen, ref Spalte);
}
}
/// Reading loop
///
/// double[] eV2 = Energy values of the current data file in eV
/// double[] meV2 = Energy values of the current data file in meV
/// double[] cm2 = Energy values of the current data file in cm^-1
/// double[] CR2 = Intensities of the current data file in CR
/// double[] CRmax2 = normalizied Intensities of the current data file in 1/CRmax
private void DataRead(string[] result, ref bool lesen, ref int Spalte)
{
for (Spalte = 0; Spalte < Anzahl; Spalte++)
{
string line;
lesen = false;
counter[Spalte] = 0;
try
{
Ursprung = openFileDialog1.FileNames[Spalte];
//initialize stream reader
System.IO.StreamReader file1 = new System.IO.StreamReader(openFileDialog1.FileNames[Spalte]);
//read line per line in stream reader
while (((line = file1.ReadLine()) != null))
{
counter[Spalte]++;
Count2 = counter[Spalte];
Count2 = Count2 / 2;
try
{
string[] splitter = line.Split(' ');
if ((splitter[0] == "S") && (splitter[1] == "0000"))
{
lesen = true;
counter[Spalte] = 0;
}
if (lesen == true)
{
//Rows will be filled an added with data value strings
if (counter[Spalte] % 2 == 0)
{
result[0] = splitter[2];
}
else
{
result[1] = splitter[2];
dataGridView1.Rows.Add();
DGV[Spalte].Rows.Add();
int Zeile = (counter[Spalte] - 1) / 2;
DGV[Spalte][0, Zeile].Value = result[0];
DGV[Spalte][1, Zeile].Value = result[1];
}
}
}
catch
{
continue;
}
}
//Streamreader is closed
file1.Close();
counter[Spalte] = counter[Spalte] / 2;
//Current datagridviw values are saved in arrays
//The conversions will be calculated and saved in new arrays
//So every unit gets its own array
double[] eV2 = new double[counter[Spalte]];
double[] meV2 = new double[counter[Spalte]];
double[] cm2 = new double[counter[Spalte]];
double[] CR2 = new double[counter[Spalte]];
double[] CRmax2 = new double[counter[Spalte]];
//Conversion calculation
for (int i = 0; i < counter[Spalte]; i++)
{
eV2[i] = Convert.ToDouble(DGV[Spalte][0, i].Value);
CR2[i] = Convert.ToDouble(DGV[Spalte][1, i].Value);
meV2[i] = 1000 * eV2[i];
cm2[i] = 8066 * eV2[i];
}
//Current file's arrays are saved in double arrays
eV[Spalte] = eV2;
CR[Spalte] = CR2;
meV[Spalte] = meV2;
cm[Spalte] = cm2;
for (int i = 0; i < counter[Spalte]; i++)
{
CRmax2[i] = CR2[i] / CR2.Max();
}
CRmax[Spalte] = CRmax2;
//Chosen conversion replaces values in datagridview
if (Hilfe == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV2[i];
}
}
else if (Hilfe == 2)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm2[i];
}
}
if (Hilfe2 == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][1, i].Value = CRmax2[i];
}
}
}
catch
{
MessageBox.Show("Es ist ein Fehler beim Einlesen eingetreten");
}
}
}
/// Energy Unit
/// Choses between eV, meV, 1/cm
/// Datagridview values are replaced by the unit array values
/// Hilfe... Saves current energy unit
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int L = comboBox1.SelectedIndex;
try
{
if (L == 0)
{
Hilfe = 1;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
}
}
catch
{
}
}
if (L == 1)
{
Hilfe = 2;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm[Spalte][i];
}
}
}
catch
{
}
}
if (L == 2)
{
Hilfe = 0;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = eV[Spalte][i];
}
}
}
catch
{
}
}
}
catch { }
}
Accept these answer if you dont know how to post your own answer?.
Answer:
Problem fixed. The reason was the dgv.autosizemode , when i deactivate it before the conversions it runs.
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
}

Categories

Resources