从onClick()添加动态添加的控件时表现不同

时间:2018-03-29 20:07:11

标签: c# forms controls

我有一个方法可以动态地将控件添加到表单中。问题是,当我从onClick调用此方法而不是初始化时,它的行为不符合预期(奇怪的间距和控件大小)。造成这种情况的原因是什么?

代码:     私有字符串fileName;

    private const int c_nameX = 12;
    private const int c_valueX = 198;
    private const int c_deltaY = 25;
    private System.Drawing.Size c_textBoxSize = new System.Drawing.Size(165, 22);
    private int v_parameterY;
    private int v_counter;

    /// <summary>
    /// default generated form constructor
    /// </summary>
    public CreateConfiguration()
    {
        v_parameterY = 121;
        v_counter = 0;
        AddParameter();
        //AddParameter();
        InitializeComponent();
    }

    /// <summary>
    /// on click for adding a new parameter field
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void AddParameter_Click(object sender, EventArgs e)
    {
        AddParameter();
    }

    private void AddParameter()
    {
        string name = "A" + v_counter++.ToString();
        string value = "B" + v_counter++.ToString();

        TextBox A = new TextBox();
        A.Name = name;
        A.Anchor = (AnchorStyles.Top | AnchorStyles.Left);
        A.Size = c_textBoxSize;
        A.Location = new System.Drawing.Point(c_nameX, v_parameterY);
        A.Visible = true;

        TextBox B = new TextBox();
        B.Name = value;
        B.Anchor = (AnchorStyles.Top | AnchorStyles.Left);
        B.Size = c_textBoxSize;
        B.Location = new System.Drawing.Point(c_valueX, v_parameterY);
        B.Visible = true;

        Controls.Add(A);
        Controls.Add(B);

        v_parameterY += c_deltaY;
    }

编辑: 图片如下。第一对文本框是初始化程序中的函数调用,第二行来自onClick

enter image description here

0 个答案:

没有答案