在循环

时间:2017-02-10 18:41:03

标签: c#

我有什么:表单上的Big PictureBox(我们称之为Pic_Map)。一个类Ore.cs,一个List<Ore> ores;和一个数据库,用于提取数据并将其放入ores列表。

功能:所以,这个功能是我有一个TextBox / Combobox和一个Button。当我按下按钮时,它将循环遍历ores列表,并基于TexBox / ComboBox等于数据(在本例中为Ore_Name)动态添加Pic_Map上的PictureBox。

问题:这一切都运行正常,但问题是,当我动态添加PictureBox时,它似乎只在ores列表中添加最后一个值(Pic_Map上的红色圆圈) )。因此,它最终只显示1个PictureBox而不是让我们说3,因为我有3个值与TextBox / ComboBox匹配的名称。

问题:如何让它像我写/选择“火焰石”一样工作,它会查看名称中包含“火焰石”的所有数据并添加它(而不是它只添加列表中的最后一个值。)

代码:

private void PopulateComboBoxByName()
    {
        PictureBox ore_Area = new PictureBox(); 

        db.GetOre(); //Getting data and putting it into "ores" list

        foreach (Ore ore in db.ores)
        {
            if (CBOX_Filter.SelectedItem.ToString() == ore.Ore_Name)
            {
                int area_Width = Convert.ToInt32(ore.Area_Width);
                int area_Height = Convert.ToInt32(ore.Area_Height);

                int ore_Width = Convert.ToInt32(ore.Ore_Width);
                int ore_Height = Convert.ToInt32(ore.Ore_Height) - area_Height / 2;
                ore_Area.Name = "ore_Area";

                ore_Area.ImageLocation = @"Data\Images\Circle.png";
                ore_Area.SizeMode = PictureBoxSizeMode.StretchImage;

                ore_Area.Size = new Size(Convert.ToInt32(area_Width), Convert.ToInt32(area_Height));
                ore_Area.Location = new Point(Convert.ToInt32(ore_Width), Convert.ToInt32(ore_Height));
                ore_Area.BackColor = Color.Transparent;

                this.Controls.Add(ore_Area);
            }
        }

        ore_Area.Parent = PIC_Map;
    }

图片:

数据: Data

地图: Dynamic Picturebox (red circle)

1 个答案:

答案 0 :(得分:0)

感谢LarsTech,它已被修复。

使图片框在循环内移动,this.controls.add更改为PIC_Map.controls.add并删除Ore_Area.Parent = PIC_Map;