Search code examples
c#variablesforeachmessagebox

MessageBox.Show to variable


I have a for each loop as follows:

foreach (PCparts parts in items)
{
    MessageBox.Show(parts.PartName);
}

The loop returns 4 values in the following order: MOBO, GFX, CPU, and RAM

Now my question is, is there a way to store just one particular value into a variable or even just display it somewhere else like in a label or whatever? For example, store GFX into a variable that can be used later.

If you haven't noticed yet, I classify myself as a newbie so please don't be too harsh. I am trying to learn.


Solution

  • Since you have items defined as List<PCParts>, you can access the objects in the list anytime you want, so long as items is in scope.

    So, for example, if you had a label (call it lblName for sake of the example), then you could do this:

    lblName.Text = items[1].PartName;
    

    Where items[1] is the second PCParts in the list (GFX).

    Essentially, sine you have the list, you already have the data stored and can retrieve it. You will need to know which item your looking for, if you're looking for a specific one. For example, to build on your for each loop:

    for each (PCpart part in items)
    {
    
        if (part.PartName == "GFX")
        {
            lblName.Text = part.PartName;
        }
    }
    

    You could also use similar logic to store a selected value in a variable for further use:

    string selectedPartName = items[1].PartName;
    

    Without knowing more about what you are trying to do, it's hard to give a more definitive answer.