简体   繁体   English

c#从数组中填充多个单元格

[英]c# populating multiple cells from array

I have an array with six numbers. 我有一个有六个数字的数组。 I'd like to perform a certain equation on each of these numbers, and then place the result in a series of textboxes, corresponding with the position within the array. 我想对这些数字中的每一个执行某个等式,然后将结果放在一系列文本框中,与数组中的位置相对应。 Eg. 例如。 result of equation on the value of pos 0 in array goes into textbox01, result of pos1 into textbox02, etc. 数组中pos 0的值的公式的结果进入textbox01,pos1的结果进入textbox02等。

I have the following code: 我有以下代码:

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);
            }
        }

I'd like to automatically change the name of the textbox (eg. txtMod01) to the following textbox in the series (txtMod02). 我想自动将文本框的名称(例如.txtMod01)更改为系列中的以下文本框(txtMod02)。

Is their any way to do this? 他们有办法做到这一点吗?

You can use reflection, which allows you manipulate types at runtime: 您可以使用反射,它允许您在运行时操作类型:

// 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;
}

You could put your Textboxs in an array as well, something like: 您可以将文本框放在一个数组中,例如:

    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];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM