在动态创建的文本框中计算

时间:2018-11-20 08:39:17

标签: c# winforms

如何在另一个文本框中的动态创建的texbox中添加值?例如,我有6个从TextBox0命名为TextBox6的文本框,我想将TextBox0中的值添加到TextBox5中,然后在TextBox6中设置该值。我该怎么办?

这是我用于创建动态文本框的代码:

static int column = 0;
private void button1_Click(object sender, EventArgs e)
{
    int i = 0;               
    if (column > 0)
    {
        do
        {
            TextBox tb = new TextBox();
            tb.Text = "";
            tb.Name = "TextBox" + (i + column * 6);
            TextBox t = (TextBox)Controls["TextBox" + i.ToString()];
            Point p = new Point(15 + (column * 125), 5 + (i * 25));
            tb.Location = p;
            this.Controls.Add(tb);
            i++;
        } while (i <= 5);
    }
    else
    {
        do
        {
            TextBox tb = new TextBox();
            tb.Text = "";
            tb.Name = "TextBox" + i;
            TextBox t = (TextBox)Controls["TextBox" + i.ToString()];
            Point p = new Point(15, 5 + (i * 25));
            tb.Location = p;
            this.Controls.Add(tb);
            i++;
        } while (i <= 5);               
    }
    column++;
}

1 个答案:

答案 0 :(得分:1)

private const string _textBoxName = "TextBox";

方法计数文本框按给定范围的文本框ID求和。请注意,如果文本框文本/名称标识不是整数或

,这将引发异常
   private int Count(int from, int to)
            {
                int GetIdFromTextBox(TextBox textBox) => int.Parse(new string(textBox.Name.Skip(_textBoxName.Length).ToArray()));

                var textBoxes = Controls.OfType<TextBox>().ToList();
                var textBoxesWithIds = textBoxes.Select(textBox => (textBox: textBox, id: GetIdFromTextBox(textBox))).ToList();

                var sum = textBoxesWithIds.Where(x => x.id >= from && x.id <= to).Sum(x => int.Parse(x.textBox.Text));

                return sum;
            }