如何从文本框数组中检索输入的文本

本文关键字:文本 检索 输入 数组 | 更新日期: 2023-09-27 18:35:36

>我正在创建一个计算器,用户在其中输入一个数字,指定用户想要多少输入(文本框)(未显示代码)。我使用文本框数组来创建这些文本框。当我想从这些文本框中获取文本来执行计算时,问题就来了,到目前为止我为此编写的代码如下所示:

int n;
TextBox[] textBoxes;
Label[] labels;
double[] values;
public void GetValue()
{
    n = Convert.ToInt16(txtInputFields.Text);
    values = new double[n];
    textBoxes = new TextBox[n];
    for (int i = 0; i < n; i++)
    {
    }
}

我不确定为此在 for 循环中放入什么;我尝试了以下方法:

 values[n] = Convert.toDouble(textBoxes[n].Text);

但它给了我一个错误:索引超出了数组的范围。

我是 C# 和一般编程的新手,因此任何帮助将不胜感激。谢谢。

编辑:创建文本框的代码如下所示:

public void InstantiateTextFields()
    {
        n = Convert.ToInt16(txtInputFields.Text);
        int posLeft = 100;
        textBoxes = new TextBox[n];
        labels = new Label[n];
        // Creates number of inputs and labels as specified in txtInputFields (n).
        for (int i = 0; i < n; i++)
        {
            textBoxes[i] = new TextBox();
            textBoxes[i].Top = 100 + (i * 30);
            textBoxes[i].Left = posLeft;
            textBoxes[i].Name = "txtInput" + (i + 1);

            labels[i] = new Label();
            labels[i].Top = 100 + (i * 30);
            labels[i].Left = posLeft - 50;
            labels[i].Text = "Input " + (i + 1);
            labels[i].Name = "lblInput" + (i + 1);
        }
        for (int i = 0; i < n; i++)
        {
            this.Controls.Add(textBoxes[i]);
            this.Controls.Add(labels[i]);
        }
    }

如何从文本框数组中检索输入的文本

GetValue 方法中的代码会重新创建文本框数组,这样做会破坏原始内容(InstantiateTextFields动态创建的文本框)。这样,您的循环就会失败,并Object Reference not set .

您只需要使用全局变量而无需重新初始化它

public void GetValue()
{
    n = Convert.ToInt16(txtInputFields.Text);
    values = new double[n];
    // textBoxes = new TextBox[n];
    for (int i = 0; i < n; i++)
    {
       values[i] = Convert.ToDouble(textBoxes[i].Text);
    }
}

关于阅读输入文本并将其转换为不加检查的双精度,有话要说。如果用户键入的内容无法转换为双精度,则代码将在 Convert.ToDouble 行上崩溃。改用

double temp;
for (int i = 0; i < n; i++)
{
   if(double.TryParse(textBoxes[i].Text, out temp)
       values[i] = temp;
   else
   {
       // Not a double value....
       // A message to your user ?
       // fill the array with 0 ?
       // Your choice....
   }
}

values[n] = Convert.toDouble(textBoxes[n].文本);给你错误,因为 n 在数组之外。您分配一个大小为 n 的数组,该数组的索引为零,即最后一个元素位于位置 n-1。

for (int i = 0; i < n; i++)
{
    values[i] = Convert.toDouble(textBoxes[i].Text);
}