首页 > 解决方案 > 如何更改动态创建的文本框的位置?

问题描述

堆栈溢出!我来过这里多次,我总是设法找到我的问题的答案!但是现在我提出了一个我找不到解决方案的问题,这里有一点 c#,当您按下按钮时会生成一个新的 TextBox,如何在创建文本框后移动它?

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int cLeft = 1;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AddNewTextBox();
        }

        public System.Windows.Forms.TextBox AddNewTextBox()
        {
            System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
            this.Controls.Add(txt);
            txt.Top = cLeft * 25;
            txt.Left = 100;
            txt.Text = "TextBox " + this.cLeft.ToString();
            cLeft = cLeft + 1;
            return txt;
        }
    }
}

标签: c#windowsvisual-studiowinforms

解决方案


要访问窗体上的动态控件,请使用控件集合。对于此示例,我在表单上添加了一个新按钮,用于移动表单上的所有文本框。

private void btnMove_Click(object sender, EventArgs e) 
{
    foreach (Control c in this.Controls)  // all controls on form
    {
        if (c is Button) continue;   // don't move buttons
        if (c is System.Windows.Forms.TextBox)  // move textboxes
            c.Top += 1;  // move down 1 pixel
            c.Left += 1;  // move right 1 pixel
    }
}

推荐阅读