【问题标题】:How to change postition of a dynamicaly created text box?如何更改动态创建的文本框的位置?
【发布时间】:2020-11-28 07:53:59
【问题描述】:

堆栈溢出!我来过这里多次,我总是设法找到我问题的答案!但是现在我提出了一个我找不到解决方案的问题,这里有一点 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;
        }
    }
}

【问题讨论】:

  • var createdTextBox = AddNewTextBox(); createdTextBox.Location = new Point(x, y);.
  • 这只适用于文本框的一个实例

标签: c# windows visual-studio winforms


【解决方案1】:

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

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

【讨论】:

  • 您能否提供一个输入示例?例如,如果它是按钮而不是文本框,每个按钮将如何区分?
  • 所有控件都有一个标签属性。您可以将其设置为字符串或链接对象。然后在代码中你可以检查if (myctrl.tag == '5') ....。您还可以链接另一个控件:mybutton.tag = mytextbox
猜你喜欢
  • 2014-01-09
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多