3
for (int f = 1; f <= 6; f++)
{
    textBox{f+11} = (loto[f].ToString());
}

您好,我正在尝试自学 C#。对不起这个noobish问题:)

更特别的是,这就是我想要的:

编写这样的代码的快捷方式:

textBox12.Text = loto[1].ToString();
textBox11.Text = loto[2].ToString();
textBox10.Text = loto[3].ToString();
textBox9.Text = loto[4].ToString();
textBox8.Text = loto[5].ToString();
textBox7.Text = loto[6].ToString();

此代码正在运行,但我想将其写在 for 循环中

4

4 回答 4

3

您可以使用字典。

Dictionary<int, TextBox> dictionary = new Dictionary<int, TextBox>();

dictionary.Add(1, textbox1);
... // add the other textboxes


// access the dictionary via index
dictionary[f+11] = ...
于 2013-04-27T08:12:53.223 回答
1

您可以在构造函数中使用 aList<TextBox>并对其进行初始化,在调用之后InitialiseComponent()您将在构造函数中看到它。

就是这样:

首先添加到您的表单类 aList<TextBox>如下:

private List<TextBox> textboxes = new List<TextBox>();

然后在构造函数中初始化列表,如下所示(更改Form1为表单构造函数的名称):

public Form1()
{
    // ...

    InitializeComponent();

    // ...

    textboxes.Add(textBox1);
    textboxes.Add(textBox2);
    textboxes.Add(textBox3);
    // ...etc up to however many text boxes you have.
}

然后当你想访问文本框时,你可以这样做:

for (int f = 1; f <= 6; ++f)
{
    textboxes[f+11].Text = loto[f].ToString(); // From your example.
}
于 2013-04-27T08:48:49.750 回答
1

我不确定您的 TextBox 控件是否已经在您的表单上。如果没有,并且您想动态创建 TextBox 控件,则可以执行以下操作:

for (int f = 1; f <= 6; f++)
{
    Dictionary<int, TextBox> dict = new Dictionary<int, TextBox>();
    dict.Add(f, new TextBox());
    dict[f].Location = new Point(0, f * 20);
    dict[f].Text = loto[f].ToString();
    this.Controls.Add(dict[f]);
}
于 2013-04-27T09:04:04.437 回答
0

你不能。您必须将它们存储在字典列表中并以这种方式访问​​它们。所以

  • 将控件添加到列表/字典
  • 在你的 for 循环中,通过索引访问它们
于 2013-04-27T08:13:27.677 回答