I am giving an array a size by what is contained in the text file. So when I look at my array it shows [4,7]. But when I read data into the array it only goes up until [1,6].
Take note that the last name is a position of the data in the array, the other entries then shows a ? sign and a no-entry sign on the right.
What is wrong with the below code?
static void buildArray()
{
int rowCount = 0;
int colCount = 0;
int placeHolder = 0;
double devideNumber = 0;
int tempNumber = 0;
string typeOptimum;
string[] objValue;
string[] constraintValues;
List<string> testNumbers;
List<double> ratioList;
List<double> rhs;
foreach (string item in constraintsList)
{
if (rowCount > 0)
{
colCount++;
}
rowCount++;
}
rowCount = colCount + 1;
colCount = colCount + 4;
string[,] arrayConstraints = new string[8, 9];
//Console.WriteLine("row {0} col {1}", colCount+1, colCount+4);
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < colCount; j++)
{
arrayConstraints[i, j] = "0";
}
}
arrayConstraints[0, 0] = "1";
objValue = constraintsList[0].Split(' ');
typeOptimum = objValue[0].ToUpper();
arrayConstraints[0, 1] = (int.Parse(objValue[1]) * -1).ToString();
arrayConstraints[0, 2] = (int.Parse(objValue[2]) * -1).ToString();
for (int i = 1; i < rowCount; i++)
{
constraintValues = constraintsList[i].Split(' ');
arrayConstraints[i, 1] = constraintValues[0];
arrayConstraints[i, 2] = constraintValues[1];
arrayConstraints[i, i + 2] = "1";
arrayConstraints[i, colCount - 1] = constraintValues[3];
}
//for (int i = 0; i < rowCount; i++)
//{
// Console.WriteLine(" ");
// for (int j = 0; j < colCount; j++)
// {
// Console.Write(arrayConstraints[i, j] + " ");
// }
//}
do
{
//Console.WriteLine(testNumbers[entryPosition]);
//Console.WriteLine(arrayConstraints[0,entryPosition+1]);
//Console.WriteLine(entryPosition+1);
testNumbers = new List<string>();
for (int i = 1; i < colCount - 1; i++)
{
testNumbers.Add(arrayConstraints[0, i]);
}
ratioList = new List<double>();
rhs = new List<double>();
for (int i = 1; i < rowCount; i++)
{
ratioList.Add(double.Parse(arrayConstraints[i, entryPosition + 1]));
rhs.Add(double.Parse(arrayConstraints[i, colCount - 1]));
}
placeHolder = findRatioTest(ratioList, rhs);
#region multiplyArray
for (int i = 0; i < rowCount; i++)
{
if (i == placeHolder)
{
devideNumber = double.Parse(arrayConstraints[entryPosition + 1, placeHolder]);
for (int j = 0; j < colCount; j++)
{
tempNumber = int.Parse(arrayConstraints[placeHolder, j]);
arrayConstraints[placeHolder, j] = (tempNumber / devideNumber).ToString();
}
}
else
{
for (int k = 0; k < colCount; k++)
{
arrayConstraints[i, k] = (double.Parse(arrayConstraints[i, k]) - (double.Parse(arrayConstraints[i, entryPosition + 1])) * double.Parse(arrayConstraints[placeHolder, k])).ToString();
}
}
}
#endregion
foreach (string item in arrayConstraints)
{
Console.WriteLine(item);
}
} while (findNumber(typeOptimum, testNumbers) == true);
//while (findNumber(typeOptimum, testNumbers) == true)
//{
// testNumbers.Clear();
// for (int i = 1; i < colCount - 1; i++)
// {
// testNumbers.Add(arrayConstraints[0, i]);
// }
//}
}
static Boolean findNumber(string type, List<string> listNumbers)
{
Boolean found = false;
int tempInt, count = 0;
tempInt = int.Parse(listNumbers[0]);
if (type == "MIN")
{
#region MIN
foreach (string item in listNumbers)
{
count++;
if (int.Parse(item) > 0 || int.Parse(item)> tempInt)
{
entryPosition = count - 1;
tempInt = int.Parse(item);
found = true;
}
}
#endregion
}
else
{
#region MAX
foreach (string item in listNumbers)
{
count++;
if (int.Parse(item) < 0 || int.Parse(item) < tempInt)
{
entryPosition = count - 1;
tempInt = int.Parse(item);
found = true;
}
}
#endregion
}
return (found);
}
static int findRatioTest(List<double> listRatio, List<double> rhs)
{
int placeHolder = 0;
List<double> ratioTest = new List<double>();
int count = 0;
double tempSmall;
int tempPlace = 0;
foreach (double item in listRatio)
{
try
{
ratioTest.Add(rhs[count]/ item);
}
catch (Exception)
{
ratioTest.Add(double.Parse("-1"));
throw;
}
count++;
}
count = 0;
tempSmall = ratioTest[0];
foreach (double item in ratioTest)
{
if (item != 0 && item > 0)
{
if (item < tempSmall)
{
tempSmall = item;
tempPlace = count;
}
}
count++;
}
placeHolder = tempPlace + 1;
ratioTest.Clear();
return (placeHolder);
}
Related
I have a neural network in visual studio. for the loss function I am using a basic cost function (pred-target)**2 and after I finish an epoch I optimize the parameter functions afterwards, but the algorithm doesn't work.
No matter what is my network configuration, the predictions are not write (it is the same output for all the inputs) and the loss function is not optimized. It stays the same through all the epochs.
void calc_lyr(int x, int y, int idx, float target) // thus function calculates the neuron value based on the previous layer
{
if (x == -1 || y == 0) // if its the first layer, get the data from input nodes
{
for (int i = 0; i < neurons[y]; i++)
{
float sum = 0;
for (int j = 0; j < inputTypes.Count; j++)
{
sum += weights[x+1][j][i] * training_test[idx][j];
}
sum = relu(sum);
vals[y+1][i] = sum;
}
}
else
{
for(int i = 0; i < neurons[y]; i++)
{
float sum = 0;
for(int j = 0; j < neurons[x]; j++)
{
sum += weights[x+1][j][i] * vals[x+1][j] + biases[y][i];
}
sum = relu(sum);
vals[y+1][i] = sum;
}
}
}
void train()
{
log("Proces de antrenare inceput ----------------- " + DateTime.Now.ToString());
vals = new List<List<float>>();
weights = new List<List<List<float>>>();
biases = new List<List<float>>();
Random randB = new Random(DateTime.Now.Millisecond);
Random randW = new Random(DateTime.Now.Millisecond);
for (int i = 0; i <= nrLayers; i++)
{
progressEpochs.Value =(int)(((float)i * (float)nrLayers) / 100.0f);
vals.Add(new List<float>());
weights.Add(new List<List<float>>());
if (i == 0)
{
for (int j = 0; j < inputTypes.Count; j++)
{
vals[i].Add(0);
}
}
else
{
biases.Add(new List<float>());
for (int j = 0; j < neurons[i-1]; j++)
{
vals[i].Add(0);
float valB = (float)randB.NextDouble();
biases[i-1].Add(valB - ((int)valB));
}
}
}
float valLB = (float)randB.NextDouble();
biases.Add(new List<float>());
biases[nrLayers].Add(valLB - ((int)valLB));
for (int i = 0; i <= nrLayers; i++)
{
if (i == 0)
{
for (int j = 0; j < inputTypes.Count; j++)
{
weights[i].Add(new List<float>());
for (int x = 0; x < neurons[i]; x++)
{
float valW = (float)randW.NextDouble();
weights[i][j].Add(valW);
}
}
}
else if (i == nrLayers)
{
for (int j = 0; j < neurons[i-1]; j++) {
weights[i].Add(new List<float>());
weights[i][j].Add(0);
}
}
else
{
for (int j = 0; j < neurons[i - 1]; j++)
{
weights[i].Add(new List<float>());
for (int x = 0; x < neurons[i]; x++)
{
float valW = (float)randW.NextDouble();
weights[i][j].Add(valW);
}
}
}
}
Random rand = new Random(DateTime.Now.Millisecond);
log("\n\n");
for (int i = 0; i < epochs; i++)
{
log("Epoch " + (i + 1).ToString() + " inceput ---> " + DateTime.Now.ToString());
int idx = rand.Next() % training_test.Count;
float target = outputsPossible.IndexOf(training_labels[idx]);
for (int j = 0; j < nrLayers; j++)
{
calc_lyr(j - 1, j, idx, target);
}
float total_val = 0;
for(int x = 0; x < neurons[nrLayers - 1]; x++)
{
float val = relu(weights[nrLayers][x][0] * vals[nrLayers][x] + biases[nrLayers][0]);
total_val += val;
}
total_val = sigmoid(total_val);
float cost_res = cost(total_val, target);
log("Epoch " + (i+1).ToString() + " terminat ----- " + DateTime.Now.ToString() + "\n");
log("Eroare epoch ---> " + (cost_res<1?"0":"") + cost_res.ToString("##.##") + "\n\n\n");
float cost_der = cost_d(total_val, target);
for (int a = 0; a < weights.Count; a++)
{
for (int b = 0; b < weights[a].Count; b++)
{
for (int c = 0; c < weights[a][b].Count; c++)
{
weights[a][b][c]-=cost_der*learning_rate * sigmoid_d(weights[a][b][c]);
}
}
}
for (int a = 0; a < nrLayers; a++)
{
for (int b = 0; b < neurons[a]; b++)
{
biases[a][b] -= cost_der * learning_rate;
}
}
}
hasTrained = true;
testBut.Enabled = hasTrained;
MessageBox.Show("Antrenament complet!");
SavePrompt sp = new SavePrompt();
sp.Show();
}
How can it be changed to optimize the weights, biases and loss function? For now, when I try to debug, the weights are changing, but it is the same value for the loss function.
I solved it by using AForge.NET: link
Datagridview calculate Amount each cell Differently based on data from database if addition then addition should be done if subtraction then subtraction to be done.
i have created this method but it affects all cell with answer. only the above cell should be calculated.
public void datagridviewone()
{
int addvalue = 0, subractvalue = 0;
ds = cs.Select("select ChargesProperty from FrieghtGridview");
list.Clear();
addition.Clear();
subtraction.Clear();
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
if(ds.Tables[0].Rows[j][0].ToString() == "Answer")
{
list.Add(j);
}
if(ds.Tables[0].Rows[j][0].ToString() == "Plus")
{
addition.Add(j);
}
if(ds.Tables[0].Rows[j][0].ToString() == "Minus")
{
subtraction.Add(j);
}
}
if (list.Count > 0)
{
for(int j = 0; j < list.Count; j++)
{
if(addition.Count > 0)
{
for(int adval = 0; adval <= addition.Count-1; adval++)
{
if
(dataGridView1.Rows[addition[adval]].Cells[3].Value.ToString()
!= "")
{
addvalue +=
Convert.ToInt32(dataGridView1.Rows[addition[adval]].Cells[3].Value);
}
}
}
if (subtraction.Count > 0)
{
for (int adval = 0; adval <= subtraction.Count - 1;
adval++)
{
if
(dataGridView1.Rows[subtraction[adval]].Cells[3].Value.ToString() != "")
{
subractvalue +=
Convert.ToInt32(dataGridView1.Rows[subtraction[adval]].Cells[3].Value);
}
}
}
var finalans = addvalue - subractvalue;
dataGridView1.Rows[list[0]].Cells[3].Value = finalans;
addvalue = 0;
subractvalue = 0;
finalans = 0;
}
}
}
I am implementing the NEH algorithm following this slide and video:
http://mams.rmit.edu.au/b5oatq61pmjl.pdf
https://www.youtube.com/watch?v=TcBzEyCQBxw
My problem during the test is the variable Sorted_list got changed which cause different results from what I expect:
This the portion where I have the problem but I couldn't know what it changes it(I used breakpoints and watch variable window):
for (int i = 0; i < kmsList.Count; i++)
{
for (int j = 0; j < kmsList[i].Length - 1; j++)
{
/*
*
* HERE Sorted_list GET MODIFIED UNEXPECTEDLY
*/
if (i == 0 && j == 0)
kmsList[0][0] = Sorted_list[0][0];
else if (i == 0)
kmsList[0][j] = kmsList[0][j - 1] + Sorted_list[0][j];
else if (j == 0)
kmsList[i][0] = kmsList[i - 1][0] + Sorted_list[i][0];
}
}
Complete implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FINAL_NEH
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("entre the nmbr of jobs : ");
string row = Console.ReadLine();
Console.WriteLine("entre the nmbr of machines : ");
string column = Console.ReadLine();
int job = int.Parse(row.ToString());
int machine = int.Parse(column.ToString());
List<int[]> list = new List<int[]>();
// read the nmbrs and put it in list-----------------------------------------------------
for (int i = 0; i < job; i++)
{
list.Add(new int[machine + 1]);
for (int j = 0; j < machine; j++)
{
list[i][j] = int.Parse(Console.ReadLine());
}
list[i][list[i].Length - 1] = int.Parse((i + 1).ToString()); //Last Elemnt Is Job Number-
}
// show the list----------------------------------------------------------------------------
for (int i = 0; i < job; i++)
{
for (int j = 0; j < machine + 1; j++)
{
Console.Write("\t" + "[" + list[i][j] + "]");
}
Console.WriteLine();
}
// sort the list------------------------------------------------------------------------------
for (int i = 0; i < list.Count; i++)
{
for (int j = i + 1; j < list.Count; j++)
{
int sumI = 0, sumJ = 0;
for (int a = 0; a < list[i].Length - 1; a++)
{
sumI += list[i][a];
}
for (int a = 0; a < list[j].Length - 1; a++)
{
sumJ += list[j][a];
}
if (sumI < sumJ)
{
int[] temp = new int[int.Parse(job.ToString())];
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
Console.Write("\n\n-----------------after sorting ------------------------------------\n\n");
// shaw the list after sorting------------------------------------------
for (int i = 0; i < job; i++)
{
for (int j = 0; j < machine + 1; j++)
{
Console.Write("\t" + "[" + list[i][j] + "]");
}
Console.WriteLine();
}
// clculate the maxpane of the first 2 jobs---------------------------------------
List<int[]> initMaxpane = new List<int[]>();
initMaxpane.Add((int[])list[0].Clone());
initMaxpane.Add((int[])list[1].Clone());
// calculer maxspan of first jobs..............................................
for (int i = 0; i < initMaxpane.Count; i++)
{
for (int j = 0; j < initMaxpane[i].Length - 1; j++)
{
if (j == 0 && i == 0)
initMaxpane[0][0] = list[i][j];
else if (i == 0)
initMaxpane[0][j] = (int)(initMaxpane[0][j - 1] + list[0][j]);
else if (j == 0)
initMaxpane[i][0] = (int)(initMaxpane[i - 1][0] + list[i][0]);
}
}
for (int i = 1; i < initMaxpane.Count; i++)
{
for (int j = 1; j < initMaxpane[i].Length - 1; j++)
{
if ((initMaxpane[i][j - 1] > initMaxpane[i - 1][j]))
initMaxpane[i][j] = (int)(initMaxpane[i][j - 1] + list[i][j]);
else
initMaxpane[i][j] = (int)(initMaxpane[i - 1][j] + list[i][j]);
}
}
int Cmax = initMaxpane[initMaxpane.Count - 1][initMaxpane[initMaxpane.Count - 1].Length - 2];
Console.WriteLine("\n\n-------the maxpane offirst jobs----------");
for (int i = 0; i < initMaxpane.Count; i++)
{
for (int j = 0; j < initMaxpane[i].Length; j++)
{
Console.Write("\t" + "[" + initMaxpane[i][j] + "]");
}
Console.WriteLine();
}
List<int[]> initMaxpane2 = new List<int[]>();
initMaxpane2.Add(list.ElementAt(1));
initMaxpane2.Add(list.ElementAt(0));
// calculer maxspan of first jobs reverse..............................................
for (int i = 0; i < initMaxpane2.Count; i++)
{
for (int j = 0; j < initMaxpane2[i].Length - 1; j++)
{
if (j == 0 && i == 0)
initMaxpane2[0][0] = list[i][j];
else if (i == 0)
initMaxpane2[0][j] = (int)(initMaxpane2[0][j - 1] + list[0][j]);
else if (j == 0)
initMaxpane2[i][0] = (int)(initMaxpane2[i - 1][0] + list[i][0]);
}
}
for (int i = 1; i < initMaxpane2.Count; i++)
{
for (int j = 1; j < initMaxpane2[i].Length - 1; j++)
{
if ((initMaxpane2[i][j - 1] > initMaxpane2[i - 1][j]))
initMaxpane2[i][j] = (int)(initMaxpane2[i][j - 1] + list[i][j]);
else
initMaxpane2[i][j] = (int)(initMaxpane2[i - 1][j] + list[i][j]);
}
}
int Cmax2 = initMaxpane2[initMaxpane2.Count - 1][initMaxpane2[initMaxpane2.Count - 1].Length - 2];
Console.WriteLine("\n\n-------the maxpane of first jobs (reverse)----------");
for (int i = 0; i < initMaxpane2.Count; i++)
{
for (int j = 0; j < initMaxpane2[i].Length; j++)
{
Console.Write("\t" + "[" + initMaxpane2[i][j] + "]");
}
Console.WriteLine();
}
List<int[]> MaxpaneList = new List<int[]>();
if (Cmax > Cmax2)
{
MaxpaneList.Add((int[])list[1].Clone());
MaxpaneList.Add((int[])list[0].Clone());
}
else
{
MaxpaneList.Add((int[])list[0].Clone());
MaxpaneList.Add((int[])list[1].Clone());
}
List<int[]> bestSequenceList = null;
List<int[]> kmsList = null;
List<int[]> Sorted_list = list.ToList();
int bestCma = 0;
//int maxspan = 0;
for (int jo = 2; jo < job; jo++)
{
for (int ins = 0; ins <= MaxpaneList.Count; ins++)
{
MaxpaneList.Insert(ins, list[jo]);
kmsList = MaxpaneList.ToList();
int Cma = 0;
for (int i = 0; i < kmsList.Count; i++)
{
for (int j = 0; j < kmsList[i].Length - 1; j++)
{
/*
*
* HERE Sorted_list GET MODIFIED UNEXPECTEDLY
*/
if (i == 0 && j == 0)
kmsList[0][0] = Sorted_list[0][0];
else if (i == 0)
kmsList[0][j] = kmsList[0][j - 1] + Sorted_list[0][j];
else if (j == 0)
kmsList[i][0] = kmsList[i - 1][0] + Sorted_list[i][0];
}
}
for (int i = 1; i < kmsList.Count; i++)
{
for (int j = 1; j < kmsList[i].Length - 1; j++)
{
if ((kmsList[i][j - 1] > kmsList[i - 1][j]))
kmsList[i][j] = kmsList[i][j - 1] + Sorted_list[i][j];
else
kmsList[i][j] = kmsList[i - 1][j] + Sorted_list[i][j];
}
}
Cma = kmsList[kmsList.Count - 1][kmsList[kmsList.Count - 1].Length - 2];
Console.WriteLine("\n\n\n------- the maxpane sequence ----------");
for (int i = 0; i < MaxpaneList.Count; i++)
{
for (int j = 0; j < MaxpaneList[i].Length; j++)
{
Console.Write("\t" + "[" + MaxpaneList[i][j] + "]");
}
Console.WriteLine();
}
Console.WriteLine("MAX : " + Cma + "\n\n\n");
if (ins == 0)
{
bestCma = Cma;
}
if (jo == 2 && ins == 0)
{
bestSequenceList = MaxpaneList.ToList();
bestCma = Cma;
}
else
{
if (bestCma > Cma)
{
bestSequenceList = MaxpaneList.ToList();
bestCma = Cma;
}
}
MaxpaneList.RemoveAt(ins);
}
MaxpaneList = bestSequenceList.ToList();
}
Console.ReadLine();
}
}
}
The issue lies in the following code (snippet):
List<int[]> Sorted_list = list.ToList();
ToList will create a new list, but because in this case int[] is a reference type then the new list will contain references to the same arrays as the original list.
Updating a value (of an array) referenced in the new list will also affect the equivalent value in the original list.
kmsList[0][0] = Sorted_list[0][0];
The solution is to create a real copy of 'list' and its items (in this case int[]):
List<int[]> Sorted_list = list.ConvertAll(myArray => (int[])myArray.Clone());
This piece of code clones all arrays within the list to a new variable Sorted_list.
A useful link that explains the difference between value and reference types is: https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
Reference Types
A reference type contains a pointer to another memory location that holds the data.
Reference types include the following:
String
All arrays, even if their elements are value types Class
types, such as Form
Delegates
When you create a List<> (or any other container) from another container (as you do when you call list.ToList()) you do not create copies of all of the elements in the container. You create new references to the items in the list that you're copying. In CS parlance it's a shallow copy and not a deep copy.
So, if you do this:
int[] ia = new[] {0, 1, 2, 3, 4};
int[] ib = new[] {5, 6, 7, 8, 9};
List<int[]> la = new List<int[]>() { ia, ib };
List<int[]> lb = la.ToList();
Both lists refer to the same two arrays, and if you change one array like this:
la[1][4] = 10;
Then lb[1][4] will also be 10 because the two lists each contain the same arrays. Copying the list does not copy the elements in the list.
I am trying to solve Gaussian elimination in c# using parallel-processing (in this case Parallel.For). My code is sometimes running fine and sometimes not.
I used as a starting point the code shown on the link: http://www.codeproject.com/Tips/388179/Linear-Equation-Solver-Gaussian-Elimination-Csharp .
I didn't use Parallel.For for back insertion just yet because there is problem with elimination.
Elimination Class:
public static bool Gauss(double[][] M)
{
int rowCount = (M.GetLength(0));
int temp = rowCount - 1;
//elimination
Parallel.For(0, temp, sourceRow =>
//for (int sourceRow = 0; sourceRow + 1 < rowCount; sourceRow++)//diagonal
{
for (int destRow = sourceRow + 1; destRow < rowCount; destRow++)//destination row
{
double df = M[sourceRow][sourceRow];
double sf = M[destRow][sourceRow];
for (int j = 0; j < rowCount + 1; j++) // line
{
M[destRow][j] = (M[destRow][j] * df - M[sourceRow][j] * sf) / df;
}
}
});
//back-insertion
for (int row = rowCount - 1; row >= 0; row--)
{
double f = M[row][row];
if (f == 0) return false;
for (int i = 0; i < rowCount + 1; i++) M[row][i] /= f;
for (int destRow = 0; destRow < row; destRow++)
{
M[destRow][rowCount] -= M[destRow][row] * M[row][rowCount];
M[destRow][row] = 0;
}
}
return true;
}
Generate Array:
public static double[][] GenerateArray2(int n)
{
Random rnd = new Random();
double[][] M = new double[n][];
for (int i = 0; i < n; i++)
{
M[i] = new double[n + 1]; // Create inner array
for (int j = 0; j < n + 1; j++)
M[i][j] = rnd.Next(-20, 20);
}
return M;
}
Print Array
public static string Print2(double[][] M)
{
string str = "";
int rowCount = M.GetUpperBound(0) + 1;
for (int row = 0; row < rowCount; row++)
{
for (int i = 0; i <= rowCount; i++)
{
str += M[row][i];
str += "\t";
}
str += Environment.NewLine;
}
return str;
}
Results are wrong in matrix 16x17 and up. At this point I don't know how to continue, I tried to lock M in elimination, didn't help.
Thanks for any help.
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;
}