简体   繁体   中英

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.

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.

In the interest of giving a different, yet equally useful answer to Tim, PCParts would be more amenable to this kind of operation if it were a Dictionary rather than a List . You'd be able to access the value corresponding to the "GFX" key with an expression like items["GFX"] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM