C# 随机数不会显示在文本框中

C# 随机数不会显示在文本框中,c#,dice,C#,Dice,无法将数字输出到文本字段,没有错误,只是无法工作 单击该按钮时,系统将关闭。错误确实会显示在文本框上,但不会显示在生成上您没有将随机数分配给文本框,而是分配了按钮。ToString: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; us

无法将数字输出到文本字段,没有错误,只是无法工作


单击该按钮时,系统将关闭。错误确实会显示在文本框上,但不会显示在生成上

您没有将
随机数
分配给文本框,而是分配了按钮。ToString:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RollTheDice
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnDice_Click(object sender, EventArgs e)
        {
            int Roll; 

            Random rand = new Random();

            Roll = rand.Next(0,10);

            diceDisplay.Text = btnDice.ToString();

        }
    }
}
此外,请精确编码并替换为一行:

int Roll; 

Random rand = new Random();

Roll = rand.Next(0,10);

diceDisplay.Text = Roll.ToString();  //modified

您应该使用roll.ToString()而不是btnDice.ToString()

好吧,你没有将文本设置为数字。您正在将其设置为btnDice.ToString()。设置diceDisplay.Text=roll.ToString()。注意这一点,通常不要将
Random
用作函数范围变量。我会把它排成一行,但是有一个预先存在的
Random
对象。你不在一个循环中,所以从技术上来说这是可以的,但是良好的实践和所有:)我发现在这个场景中没有什么不同。他已经在一个文本框中保存了它。重复的调用(如果你可以足够快地点击)会导致显示相同的值。将其存储为off可修复此问题(与不在循环中使用
Random
的原因相同)。你点击的速度不够快,所以没问题(这就是我评论的限制)。@BradleyDotNET我想你的意思是:(同样的原因,你不在循环中使用
newrandom();
)。是的,这就是我的意思。我所说的
Random
newrandom()
应该被替换掉。谢谢!那确实管用!
diceDisplay.Text = new Random().Next(0,10).ToString();