Home > other >  C# Forms App - Combo Box with an Array of strings as the Data source, how to set combo box value bas
C# Forms App - Combo Box with an Array of strings as the Data source, how to set combo box value bas

Time:08-03

I have an array of strings with 41 different strings, I have a combo box on a couple different forms and I set the values of that Combo Box using that array as the data source.

public static readonly string[] array1 = { "Value 1", "Value 2", etc. }
WLSel.DataSource = WavelengthArray.array1; 

The program itself takes the user input and exports all of the data to a .txt file, and I'm building the capability to import that same .txt file and load the form with that known data. I've been successful in setting more simple combo boxes, and radio buttons based on known values, but I've hit a road block because of the 41 values possible in this array.

Is there a way I can grab that value from the .txt, and basically ask the program to check that array, and if you find something equal, set the SelectedIndex to that value, or do I need to just write a switch with each case?

Would a foreach block work? If I do a foreach to check each item in the array and compare it with my known value and come across a match, what would be the easiest way to grab the index of that value so I can input it into the Combo Box?

CodePudding user response:

If I understood correctly, you are trying to populate the combobox from a .txt file. You can write each value one per line, read the content of the file and then pass the content to the combobox as follows:

string[] fileContent = System.IO.File.ReadAllLines(<<file_path>>);
WLSel.DataSource = fileContent;

Consider using an OpenFileDialog to get the <<file_path>>.

CodePudding user response:

I figured it out, I used the following to check each value in the array, then grab the index of when the expected value occurs and set the Combo Box to that value.

string WL = Wavelength; 
foreach (string Value in WavelengthArray.array1)
{
   if (Value == WL)
   {
      int WLIdx = Array.IndexOf(WavelengthArray,Array1, Value);
      WLSel.SelectedIndex = WLIdx;
   }
}
  • Related