MrAnderson1992
MrAnderson1992

Reputation: 409

How to add items to an array to replace variables

I am looking at creating an array of string based variables in order to understand which text boxes have been checked, for example:

string[] checkedItems = new string[10];

        foreach (object item in checkedList.CheckedItems)
        {
            checkedItems.SetValue(item, 0);                                                         
        }

I need this to basically, understand which checkboxes have been ticked, then show the results.

Later the results will be used to compare excel spreadsheets. So with that understanding each item is a "Column"

I have also tried writing:

checkedItems.SetValue(item, 0);
checkedItems.SetValue(item, 1);
checkedItems.SetValue(item, 2);
checkedItems.SetValue(item, 3);

This just shows for example:

Array slot 1 = DocID
Array slot 2 = DocID
Array slot 3 = DocID.

I believe this is because it is just looping for every checkbox. There are 10.

Upvotes: 3

Views: 62

Answers (1)

IAbstract
IAbstract

Reputation: 19871

Following the information on MSDN, the example shows:

foreach(object itemChecked in checkedListBox1.CheckedItems) {

    // Use the IndexOf method to get the index of an item.
    MessageBox.Show("Item with title: \"" + itemChecked.ToString() + 
                    "\", is checked. Checked state is: " + 
                    checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(itemChecked)).ToString() + ".");
}

To adapt it to your question, we might do this:

string[] GetCheckedItems() {
    //  use a list because the number is not interrogated
    var checkedItems = new List<string>();

        foreach (object item in checkedList.CheckedItems) {
            checkedItems.Add(item.ToString());                                                         
        }

    return checkedItems.ToArray();
}

... or you can interrogate the number of checked items:

string[] GetCheckedItems() {
    //  interrogate checked items count
    var checkedItems = new string[checkedList.CheckedItems.Count];

        for (int i = 0; i < checkedItems.Length; i++) {
            checkedItems[i] = checkedList.CheckedItems[i].ToString();                                                         
        }

    return checkedItems;
}

... or if you feel comfortable with Linq:

string[] GetCheckedItems() {
    return checkedList.CheckedItems
        .Select(ci => ci.ToString())
        .ToArray();
}

Upvotes: 2

Related Questions