1

我有一个包含六个数字的数组。我想对这些数字中的每一个执行某个等式,然后将结果放在一系列文本框中,与数组中的位置相对应。例如。数组中 pos 0 的值的方程结果进入 textbox01,pos1 的结果进入 textbox02 等。

我有以下代码:

for (int i = 0; i <= 5; i++)
        {
            if ((Convert.ToInt32(statArray.GetValue(i))-10)%2 == 0)
            {
                //txtMod01.Text = Convert.ToString((Convert.ToInt32(statArray.GetValue(i)) - 10) / 2);
            }
            else
            {
                txtMod01.Text = Convert.ToString((Convert.ToInt32(statArray.GetValue(i)) - 11) / 2);
            }
        }

我想自动将文本框的名称(例如 txtMod01)更改为系列中的以下文本框(txtMod02)。

他们有什么办法吗?

4

2 回答 2

2

您可以使用反射,它允许您在运行时操作类型:

// property name "txtMod0x"
string propertyName = "txtMod" + i.ToString().PadLeft(2, '0');

// get the property from the current type
PropertyInfo prop = this.GetType().GetProperty(propertyName);

if (prop != null)
{
    // get the property value (the TextBox in this case)
    var textBox = (TextBox)prop.GetValue(this, null);

    string val = Convert.ToString((Convert.ToInt32(statArray.GetValue(i)) - 11) / 2);
    textBox.Text = val;
}
于 2013-10-08T22:45:17.360 回答
1

您也可以将您的文本框放入一个数组中,例如:

    TextBox[] boxes = new TextBox[]{txtbox01, txtbox02, txtbox03, txtbox04, txtbox05, txtbox06};
    int[] values = new int[]{val1, val2,val3, val4,val5, val6};
    for(int i=0; i < values.Count; ++i)
    {
        //perform calculations

        ...

        boxes[i].Text = values[i];
    }
于 2013-10-09T01:23:41.097 回答