populating multiple comboBoxes from elements in a string list - c#

I have a list of input curve names in a text file called inCurves.txt. The .txt file reads:
18500*8500*Eval:c3*Eval:c2*Eval:c1*Final:DTS*Final:OBG*Final:PPG*
The first two numbers are bottom and top depth, while the remainder are curveSet names and curve names for every remaining comboBox (1 - 6)
I've written a script to populate comboBoxes from this .txt, but I receive an error when I try to convert cmbBox into string, and then into an integer.
input string was not in a correct format)
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
string CurveNamesInText = "";
char[] delimiter = { '*' };
CurveNamesInText = System.IO.File.ReadAllText(#"C:\Users\Public\inCurves.txt");
string[] crvIn = CurveNamesInText.Split(delimiter);
string BottomDepth = crvIn[0];
string TopDepth = crvIn[1];
var combBoxes = this.Controls.OfType<ComboBox>().Where(x => x.Name.StartsWith("comboBox"));
foreach (var cmbBox in combBoxes)
{
string yes = Convert.ToString(cmbBox);
string number = yes.Replace("comboBox","0");
int i = Convert.ToInt16(number); //error here, comp doesn't like it
MessageBox.Show("current number value \n" + number + "\n" + "current i value \n" + i);
//cmbBox.Text = crvIn[6-i]; // this is what I'd like to do next
}
}
catch (Exception ex)
{
MessageBox.Show("Error Loading Curve names \n" + ex.Message + "\n" + ex.StackTrace);
}
}
I would like to assign an element in crvIn list to each comboBox. Ideally, something like this:
cmbBox.Text = crvIn[i];
Can you help?

The problem is that you are trying to convert an entire object ComboBox into a string, which will result only in the full name of the class/type ComboBox plus the item count:
"System.Windows.Controls.ComboBox Items.Count:0"
You can also see this in the Debugger.
I would like to assign an element in crvIn list to each comboBox
I guess if you want to add each value to a different combobox you could use a for-loop and add the items. You need to add it to the items, if you want to make them selectable.
First you need to make a list from your query. Add ToList() at the end:
var combBoxes = this.Controls.OfType<ComboBox>()
.Where(x => x.Name.StartsWith("comboBox")).ToList();
for (int i = 0; i < combBoxes.Count; i++)
{
combBoxes[i].Text = crvIn[i + 2];
}

Related

How to get data out of a foreach and reuse in while and do while in c#?

In the Foreach the data has loop exactly but when the data send to while, It display single character only of each data for example: exact data is: "John" but in my code it display: J then next O, H, N until each character of the exact data is finished. Code example below:
foreach (DataGridViewRow row in DataGrid2.Rows)
{
bool isSelected = Convert.ToBoolean(row.Cells["ChkOkay"].Value);
if (isSelected)
{
value += row.Cells["EnrollName"].Value.ToString();
Console.Writeline("Selected Values " + value);
}
}
while (v < value.Length())
{
do
{
//It display single character only instead whole name.
MessageBox.Show("Name: "value[v] + "Slot: " + u);
foreach (var chari in value[v].ToString())
{
//I re use the data here from 1st foreach
}
v++;
u += 51;
} while (u < 5559);
I did not understand your code, but the correct form is to take a column of DataGrid rows and place it in a list.
You then print the list elements and then check the characters of each list item.
List<string> EnrollNameList = new List<string>();
foreach (DataGridViewRow row in DataGrid2.Rows)
{
bool isSelected = Convert.ToBoolean(row.Cells["ChkOkay"].Value);
if (isSelected)
{
string colValue = row.Cells["EnrollName"].Value.ToString();
EnrollNameList.Add(colValue);
Console.WriteLine("Selected Values " + colValue);
}
}
int v = 0;
while (v < EnrollNameList.Count)
{
//message box show whole EnrollName
MessageBox.Show("Name: " + EnrollNameList[v]);
foreach (var chari in EnrollNameList[v])
{
//get each char in EnrollName
}
v++;
}
strings can be indexed like arrays. Treating a string like an array (and adding an indexer in square brackets) returns the char at that position in the string.. "John"[0] is 'J'. Your value is a single string, not an array of strings.
With this:
value += row.Cells["EnrollName"].Value.ToString();
You're making a string value a longer and longer string. If your grid has 3 rows containing "mark", "luke" and "john", your value ends up as "marklukejohn"
If you then loop over it, you messagebox it out a char at a time
I suspect you want to retain the strings as whole strings (3 of them) in an array (or list).. in which case:
var names = new List<string>();
foreach ....
names.Add(row.Cells["EnrollName"].Value.ToString())
Then you can later loop over the list and pull the names out as complete strings
while (v < names.Count)
{
MessageBox.Show("Name: " + names[v] + "Slot: " + u);
Your code is full of syntax errors and won't compile. Do try to get code working before you post it unless the question is about a compiler error

Duplicates using Arrays and TextFile

I'm having an issue outputting my current code in Unity. I'm using an output text field to display the amount of duplicates per number.
Been browsing feeds and haven't gotten what I needed so here I am asking this now.
public int whatIndex,count;
public Text output;
public void Start()
{
string Random = "";
//reading the text file
string Duplicates = "duplicates.txt";
string Duplicates_Path = Application.dataPath + "/Text_Files/" + Duplicates;
string[] Numbers = File.ReadAllLines(Duplicates_Path);
foreach(string number in Numbers)
{
Random += number;
}
output.text = Random + "\n";
//array for text
for (whatIndex = 0; whatIndex < Duplicates.Length; whatIndex++)
{
Debug.Log(Numbers[whatIndex] + "\n");
Debug.Log("The number " + Numbers[whatIndex].ToString() + " appears " + count +
" times(s)");
}
}
As I understand you want to count occurrence for each number which is available in duplicate.txt files. Please find below code, i have tweak your code little bit e.g. file path and debug.log and remove unnecessary variables. you can see input here and output here:
public void Start()
{
Dictionary<int, int> numberCount = new Dictionary<int, int>();
//reading the text file
string Duplicates = "duplicates.txt";
string Duplicates_Path = Environment.CurrentDirectory + "\\Text_Files\\" + Duplicates;
string[] Numbers = File.ReadAllLines(Duplicates_Path);
foreach (string number in Numbers)
{
int temp = int.Parse(number);
if (numberCount.ContainsKey(temp))
{
numberCount[temp] = numberCount[temp] + 1;
}
else
{
numberCount[temp] = 1;
}
}
//array for text
foreach(KeyValuePair<int,int> item in numberCount)
{
Console.WriteLine("The number " + item.Key.ToString() + " appears " + item.Value.ToString() +
" times(s)");
}
}
I am not sure, what you want to achieve but I guess, there are some problems with your code (see after code).
Example Snippet:
First of all, you can try to use this code to get an idea about one solution to get the duplicates and the number of duplicates after reading the text file by using a Dictionary from System.Collections.Generic:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// String array with duplicates
string[] Numbers = {"1","1", "2", "6","1","7","1","7","8","3"};
Dictionary<string, int> KeyNumbersValueCount = new Dictionary<string, int>();
foreach(string number in Numbers)
{
if(KeyNumbersValueCount.ContainsKey(number))
KeyNumbersValueCount[number] += 1;
else
KeyNumbersValueCount.Add(number, 1);
}
foreach(var NumberAndCount in KeyNumbersValueCount)
Console.WriteLine("The number " + NumberAndCount.Key + " appears " +
NumberAndCount.Value + " times(s)");
}
}
running example code above
Open Issues with your code from the question:
Do you need count? It is initializied but never used
If you don't need "whatIndex", then you can also initialize it within the for loop:
for (int whatIndex = 0; whatIndex < Duplicates.Length; whatIndex++)
{
// do s.th.
}
You are trying to iterate over length of the string "Duplicates", which is "duplicates.txt" and therefore it has a length of 14. I guess you want to iterate over your strings in your file.
In your case, Random doesn't really have a function. You could also use File.ReadAllText instead of File.ReadAllLines and hand it over to output.text, if you only want to print it. See Microsoft Refs.

convert number index of string array to double array

I am reading from a text file, pulling each line, looking for the first line with 1|, and then converting it into an array. For this I only want the 4th index so that I can sum and count the array.
Here is what is converts from the text file into an array
1|123456|01/06/2019|123456|100.00|USD|DUE UPON RECEIPT|TEST1||98790125|TEST2|TEST3|N
so [0] = 1, [2] = 123456, etc. etc. I am trying to pull 100.00 from it and put it in it's own array, so that I can easily double sum, and count the elements. It's proving difficult for me since the original array is a string though.
I've tried creating a separate string array already split, and then pulling the 4th index and creating an double array that I can count and sum. I've also tried just splitting and creating an int array in one line from the str it pulls.
string str;
using (StreamReader file = new StreamReader("c:\\testdoc.txt"))
while ((str = file.ReadLine()) != null)
{
string[] strArray = str.Split('|');
if (strArray[0] == "1")
{
double[] itotals = strArray.Select(i => Convert.ToDouble(i)).ToArray();
int count = itotals.Length;
double amt = itotals.Sum();
Console.WriteLine("Count: " + count + " Amt: " + amt);
}
else
{
}
}
I expect it to find the line starting with 1|, then tell console to write count: 1 amt: 100.00, but I actually just get errors that input strings were not in the correct format. I know that I need to pull the 4th index after I split, but I'm not sure where to do that.
Try this
string str;
int count = 0;
double amt = 0;
using (StreamReader file = new StreamReader("c:\\testdoc.txt"))
while ((str = file.ReadLine()) != null)
{
string[] strArray = str.Split('|');
if (strArray[0] == "1")
{
string itotals = strArray[4];
count = count+1;
amt = amt + Convert.ToDouble(strArray[4]);
Console.WriteLine("Count: " + count + " Amt: " + amt);
}
else
{
}
}

Get a single string out of a ListBox Item

I have a ListBox with X Items in it. An Item is build up like String, double, double. I want that the item with the smalles value of the second double gets shown together with its string in a Label.
An example Item: Name Value1 Value2
So every part is devided by spaces. The code works only for getting the smallest value of the second double yet, but doesnt take the string of that item.
The function of vName doesn't work.
private void bVergleich_Click(object sender, RoutedEventArgs e)
{
if (listBox.Items.Count <= 0)
{
MessageBox.Show("Bitte erst Einträge hinzufügen.");
}
else
{
int anzahl = listBox.Items.Count;
string str = listBox.Items[anzahl].ToString();
string vName = str.Substring(0, str.IndexOf(" ") + 1);
var numbers = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').First(), NumberStyles.Currency, CultureInfo.CurrentCulture));
decimal minValue = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture)).Min();
lVergleich.Content = vName + " " + minValue + "€";
}
}
Any ideas how I can get the string too?
I will try using your code example. You could use the old school approach and run with a for-loop through all entries.
private void bVergleich_Click(object sender, RoutedEventArgs e)
{
if (listBox.Items.Count <= 0)
{
MessageBox.Show("Bitte erst Einträge hinzufügen.");
}
else
{
List<decimal> tmpListe = new List<decimal>();
int anzahl = listBox.Items.Count;
for (int i = 0; i < anzahl; i++)
{
string str = listBox.Items[i].ToString();
// collect all the second double values
tmpListe.Add(decimal.Parse(str.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture));
}
// get the minimal value and its index
decimal minValue = tmpListe.Min();
int index = tmpListe.IndexOf(tmpListe.Min());
// use the index to get the name
string str2 = listBox.Items[index].ToString();
string vName = str2.Substring(0, str2.IndexOf(" ") + 1);
// write down your comparison
lVergleich.Content = vName + " " + minValue + "€";
}
}
This should display you the first lowest value in your List.
personally I would also suggest to use a custom class with 3 properties and an overridden ToString method for display. Then collect all the items in a generic List and bind this List to the ListBox.
You can sort your collection by the desired value and take the first element in sequence
List<string> list = listBox.Items.ToList();
list.Sort((x1, x2) => decimal.Compare(decimal.Parse(x1.Split(' ')[1]), decimal.Parse(x2.Split(' ')[1])));
string x = list.First();
Or just
string result = listBox.Items.OrderBy(y => decimal.Parse(y.Split(' ')[1])).First();

Data lost while adding string to listbox

I am cycling through the contents of a two-dimensional array containing the result of a Punnett Square calculation for gene crosses. I need to summarize the result so that the user can readily see the unique instances. I can accomplish this by putting the result into a text box, but when I try and use a ListBox to display the data, part of the information is getting lost, namely a translation of the AaBBCc type data to something that directly relates to the traits that the user initially selected.
This is the main block of code for the operation:
foreach (string strCombination in arrUniqueCombinations)
{
int intUniqueCount = 0;
decimal decPercentage;
foreach (string strCrossResult in arrPunnettSQ)
{
if (strCrossResult == strCombination)
{
intUniqueCount++;
}
}
decPercentage = Convert.ToDecimal((intUniqueCount*100)) / Convert.ToDecimal(intPossibleCombinations);
txtReport.AppendText(strCombination + " appears " + intUniqueCount.ToString() + " times or " + decPercentage.ToString() + "%."+ Environment.NewLine);
lstCrossResult.Items.Add(DecodeGenome(strCombination) + " appears " + intUniqueCount.ToString() + " times or " + decPercentage.ToString() + "%.");
}
For appending the data to the textbox I use this code and it works perfectly:
txtReport.AppendText(DecodeGenome(strCombination) + " appears " + intUniqueCount.ToString() + " times or " + decPercentage.ToString() + "%."+ Environment.NewLine);
Giving the result:
Trait 1 Het.,Trait 3 appears 16 times or 25%.
For adding the result to a list box, this works:
lstCrossResult.Items.Add(strCombination + " appears " + intUniqueCount.ToString() + " times or " + decPercentage.ToString() + "%.");
Giving the result:
AaBBCc appears 16 times or 25%.
But the contents of strCombination is AaBBCc and I need it translated to "Trait 1 Het.,Trait 3", which I accomplish with this bit of code:
private string DecodeGenome(string strGenome)
{
string strTranslation = "";
int intLength = strGenome.Length;
int intCounter = intLength / 2;
string[] arrPairs = new string[intLength / 2];
//Break out trait pairs and load into array
for (int i = 1; i <= intLength; i++)
{
arrPairs[i / 2] = strGenome.Substring((i-1),2);
i++;
}
foreach (string strPair in arrPairs)
{
char chFirstLetter = strPair[0];
char chSecondLetter = strPair[1];
intCounter = intCounter - 1;
if (Char.IsUpper(chFirstLetter))
{
if (!Char.IsUpper(chSecondLetter))
{
if (intCounter > 0)
{
txtReport.AppendText(GetDescription(strPair.Substring(0, 1)) + " Het.,");
}
else
{
txtReport.AppendText(GetDescription(strPair.Substring(0, 1)));
}
}
}
else
{
if (!Char.IsUpper(chSecondLetter))
{
if (intCounter > 0)
{
txtReport.AppendText(GetDescription(strPair.Substring(0, 1)) + ",");
}
else
{
txtReport.AppendText(GetDescription(strPair.Substring(0, 1)));
}
}
}
}
return strTranslation;
}
That has no problem displaying in a text box, but when I try and put it as an item into a list box it turns it into null. Instead of:
"Trait 1 Het.,Trait 3 appears 16 times or 25%."
I get:
" appears 16 times or 25%."
I have tried adding the results to an ArrayList, then populating the listbox after everything is processed, but the result is the same.
Any clues as to why the list box is not accepting the translated AaBBCc information would be greatly appreciated.
strTranslation is never set. Everything is pushed to txtReport.AppendText

Categories

Resources