从数组属性分配随机文本框

时间:2019-01-13 17:50:03

标签: c#

我对使用C#进行编码非常陌生,而且很难将属性从数组分配给随机文本框。这是我正在使用的代码:

TextBox[] peopletiles = { A2, A3, A4, A5,};
int totalpeople = 0; 

do
{
    Random random = new Random();
    int tile = random.Next(0, peopletiles.Length);
    tile.BackColor = Color.Purple;                    
    totalpeople += 1;
} while (totalpeople != Edit.peopleStart);                    

我正在尝试将随机文本框的颜色从数组“ peopletiles”更改为紫色,并使其循环播放,直到紫色文本框的数量等于“ Edit.peopleStart”的值为止。

使用上面的代码将给出错误“'int'不包含'BackColor'的定义”

2 个答案:

答案 0 :(得分:1)

您尝试在此代码中设置int而不是文本框的属性:

int tile = random.Next(0, peopletiles.Length);
tile.BackColor = Color.Purple; 

您想尝试

var tile = peopletiles[random.Next(0, peopletiles.Length)];
tile.BackColor = Color.Purple; 

此外,如评论中所述,您不应在循环中创建新的Random(),而应在循环之外(甚至在类级别仅创建一次)

答案 1 :(得分:1)

controller变量带到循环外,这在使用Random时很重要。另外,您需要稍微修改一下循环。改用List,并在每次迭代中选择随机TextBox,更改颜色并将其从临时列表中删除。

[Authorize]
[Route("api/camps/{moniker}/speakers")]
[ValidateModel]
[ApiVersion("1.0")]
[ApiVersion("1.1")]
public class SpeakersController : BaseController

  [HttpGet]
  [MapToApiVersion("1.0")]
  [AllowAnonymous]
  public virtual IActionResult Get(string moniker, bool includeTalks = false)



[Route("api/camps/{moniker}/speakers")]
public class Speakers2Controller : SpeakersController

  public override IActionResult Get(string moniker, bool includeTalks = false)
  {  return NotFound(); }

  [ApiVersion("2.0")]
  public override IActionResult GetWithCount(string moniker, bool includeTalks = false)