C#WinForms,在运行时和控件中动态添加usercontrol是不可见的?

时间:2013-09-03 02:46:47

标签: c# winforms user-controls visible dynamically-generated

我正在联系经理,我想将联系人详细信息的控件添加到用户控件中,例如电话号码,电子邮件。我创建了一个名为TextPrompt的用户控件,其中包含一个标签和文本框。代码应该通过联系人信息排序并为每个主菜添加一个控件,程序不会产生任何错误(逻辑和语法,据我所知)。我运行检查以确保在循环运行后控件被添加到面板中并显示控件在那里,但它们在运行时不可见。

        List<ContactType> details = contact.ReturnAllContactDetails();
        int y = 0;

        if (contact != null)
        {
            lbl_Name.Text = "";
            if (contact.GetContactValueByType("FirstName") != null) { lbl_Name.Text = contact.GetContactValueByType("FirstName") + " "; }
            if (contact.GetContactValueByType("LastName") != null) { lbl_Name.Text = lbl_Name.Text + contact.GetContactValueByType("LastName"); }
            if (contact.GetContactValueByType("Company") != null) { lbl_Name.Text = lbl_Name.Text + "\n" + contact.GetContactValueByType("Company"); }

            pnl_ContactDetails.BringToFront();
            pnl_ContactDetails.Controls.Clear();
            pnl_ContactDetails.SuspendLayout();
            for(int i = 3; i < details.Count; i++) {
                TextPrompt txtbox = new TextPrompt(details[i]);                 //Textbox to be added
                MessageBox.Show(details[i].value);
                this.pnl_ContactDetails.Controls.Add(txtbox);

                txtbox.Name = details[i].name;                                  //Sets properties
                txtbox.Location = new Point(25, y);
                txtbox.Size = new System.Drawing.Size(345, 45);
                txtbox.TextValueChanged += new EventHandler(txtbox_TextChanged);
                txtbox.Show();

                txtbox = (TextPrompt)this.pnl_ContactDetails.Controls[i - 3];   //Checks to make sure controls are on form.
                MessageBox.Show(txtbox.ContactDetails.name);

                y = y + 45;
            }
        }

1 个答案:

答案 0 :(得分:2)

您似乎在没有告诉专家组SuspendLayout()

的情况下致电ResumeLayout()
pnl_ContactDetails.SuspendLayout();
for(int i = 3; i < details.Count; i++)
{
    TextPrompt txtbox = new TextPrompt(details[i]); //Textbox to be added
    MessageBox.Show(details[i].value);

    txtbox.Name = details[i].name; //Sets properties
    txtbox.Location = new Point(25, y);
    txtbox.Size = new System.Drawing.Size(345, 45);
    txtbox.TextValueChanged += new EventHandler(txtbox_TextChanged);
    /* txtbox.Show(); */ // Leave this call out in favor of:
    txtbox.Visible = true;
    this.pnl_ContactDetails.Controls.Add(txtbox);

    txtbox = (TextPrompt)this.pnl_ContactDetails.Controls[i - 3]; //Checks to make sure controls are on form.
    MessageBox.Show(txtbox.ContactDetails.name);

    y = y + 45;
}
pnl_ContactDetails.ResumeLayout();

我对您的代码进行了一些修改。警告Emptor: - )