endlessforms
endlessforms

Reputation: 15

populating multiple comboBoxes from elements in a string list

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?

Upvotes: 1

Views: 127

Answers (1)

Mong Zhu
Mong Zhu

Reputation: 23732

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];
}

Upvotes: 2

Related Questions