对于循环通过PictureBoxes而在c#上没有数组

char SideA = 'A';
char SideB = 'B';
int CPUPlayer = 1;
Test.Text = x.ToString();

if (difficulty == 1)
{ 
    if (CPUPlayer == 1)
    {

        string targetString = "";
        for (int side = 1; side <= 1; side++)
        {

            targetString = SideA.ToString();
            Test.Text = targetString.ToString();
            for (int game = 1; game < 25; game++)
            {
                targetString = game.ToString();
                for (int tile = 1; tile < 10; tile++)
                {
                    targetString = tile.ToString();
                    PictureBox target = (PictureBox)(this.Controls.Find(targetString,true))[0];
                    if (target.BackgroundImage == null)
                    {
                        target.BackgroundImage = Properties.Resources.smallo;
                        Test.Text = targetString.ToString();
                    }
                }
            }

        }
    }
}

因此,我尝试通过命名的PictureBox(例如A11,A12,A13等)进行循环,以使它们通过使用循环字符串连接到图片框来更改背景图片,但我一直在{{ 1}}来自Index is out of range

我不确定该如何解决。我对C#和编码通常还是很陌生,所以很高兴知道我缺少什么!

octer_liu 回答:对于循环通过PictureBoxes而在c#上没有数组

为帮助您找到问题的改变

PictureBox target = (PictureBox)(this.Controls.Find(targetString,true))[0];

var found = this.Controls.Find(targetString,true);

if(found == null || found.Length < 1 ) {
  throw new Exception("Picture not found")
}

然后,在throw行中设置一个断点,并找出为什么找不到图片。

,

因此,事实证明,只是我的.ToString();逻辑完全错误,并且字符串以不存在的图片框的形式出现。这是有效的代码:

            if (difficulty == 1)
        { 
            if (CPUPlayer == 1)
            {

                string targetString = "";
                for (int side = 1; side <= 1; side++)
                { 
                    for (int game = 1; game < 25; game++)
                    {

                        for (int tile = 1; tile < 10; tile++)
                        {
                            targetString = SideA;
                            targetString += game.ToString();
                            targetString += tile.ToString();
                            Test.Text = targetString.ToString();
                            PictureBox target = (PictureBox)(this.Controls.Find(targetString,true))[0];
本文链接:https://www.f2er.com/3169886.html

大家都在问