【问题标题】:Putting values of an array into text boxes using C#使用 C# 将数组的值放入文本框中
【发布时间】:2021-09-20 11:47:32
【问题描述】:

我已经使用两个for 循环创建了一个维度数组,并且随着每个内部循环的完成,我希望将这些值放入 Windows 窗体上的文本框中。 (我意识到每次都会覆盖这些值,最后只显示来自最终外部循环的值。)

代码中的 cmets 显示了我一直在努力工作的内容。

谢谢!

if (IsValidData())
{
    int Columns = 5;
    int Rows = Convert.ToInt32(txtNumbDrawings.Text);
    
    int[,] ball = new int[Columns, Rows];

    for (int i = 0; i < Rows; i++)
    {
        List<int> ballsList = new List<int>();
        int[] txtBall = new int[Columns];

        for (int j = 0; j < Columns; j++)
        {
            Random number = new Random();
            ball[i, j] = number.Next(1, 70);
            
            // prevent duplicate numbers
            while (ballsList.Contains(ball[i, j] ))
            {
                ball[i, j] = number.Next(1, 70);
            }
            
            ballsList.Add(ball[i, j]);

            /*************************************************
             * how do I get the current ball value
             * into a textbox on a form?
             * 
             * textboxes are named txtBall1, txtBall2, etc...
             * 
             * I was trying something like:
             * 
             * TextBox[] txtBall = new TextBox[5];
             * for (int i = 0; i < 5; i++)
             * {
             *      txtBall[i + 1].Text = ball[i, j].ToString();
             * }
             *************************************************/
        }

        ballsList = null;
    }
}

Windows Form Image:  https://1drv.ms/u/s!Ak6hxvO3Ye6Oj5I9NQy834Yk4TRLyw?e=DniwK8

【问题讨论】:

  • 你对这段代码有什么期望?
  • 将每个lstBall1 放入一个数组并索引该数组。
  • 有多少张图纸?

标签: c# arrays winforms


【解决方案1】:

如果我理解您要做什么,并且似乎将一个打乱的整数列表分配给 5 个列表框之一,那么应该这样做:

if (IsValidData())
{
    Random rnd = new Random();
    
    // (1, 69) because rnd.Next(1, 70) only produces the numbers 1 to 69
    int[] shuffled_balls = Enumerable.Range(1, 69).OrderBy(x => rnd.Next()).ToArray();

    ListBox[] list_boxes = new [] { lstBall1, lstBall2, lstBall3, lstBall4, lstBall5 };

    for (int i = 0; i < shuffled_balls.Length; i++)
    {
        list_boxes[i % list_boxes.Length].Items.Add(shuffled_balls[i]);
    }
}

【讨论】:

  • 我说错了,我试图将整数添加到文本框,而不是列表框。这只是一个学习/练习的东西,强力球。所以我要画 5 个伪随机白球,然后是 1 个红色强力球。图纸的数量基于用户输入数字的 txtbox。我将使用更正/附加信息编辑我的原始帖子。谢谢!
猜你喜欢
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多