C#WinForms,在运行时动态添加用户控件,控件不可见
本文关键字:控件 用户 添加 运行时 动态 C#WinForms | 更新日期: 2023-09-27 18:29:54
我正在开发一个联系人管理器,我想添加联系人详细信息的控件,如电话号码、给用户的电子邮件控件。我创建了一个名为TextPrompt的用户控件,其中包括一个标签和文本框。代码应该对contacts Info进行排序,并为每个entre添加一个控件,程序不会产生错误(据我所知,是逻辑和语法错误)。我运行了检查,以确保在循环运行后将控件添加到面板中,它显示控件在那里,但在运行时它们不可见。
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;
}
}
您似乎调用了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();
我对你的代码做了一些修改。Cavat Emptor:-)