2016-08-01 13 views
0

Ich versuche, ein Benutzersteuerelement mit einem Windows Forms Panel und Nummer Label s mit einigen Text dynamisch zur Panel horizontal hinzugefügt. Ich versuche mit unter Code und die Label s übersteuert.Benutzer Kontrolle mit Panel und Etiketten dynamisch horizontal hinzugefügt

public partial class AllergyBar : Panel 
{ 
    public AllergyBar() 
     : base() 
    { 
     InitializeComponent(); 
    } 

    int X = 0, Y=0; 

    int height, width; 
    public AllergyBar(List<String> lstAlerts) 
     : base() 
    { 

     this.BackColor = System.Drawing.Color.WhiteSmoke; 
     this.Name = "panel2"; 
     this.Size = new System.Drawing.Size(75, 23); 
     this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; 
     foreach (string alert in lstAlerts) 
     { 
      Label AllergyLabel = new Label(); 
      AllergyLabel.Text = alert; 
      width = AllergyLabel.Size.Width; 
      Y = AllergyLabel.Location.Y; 
      AllergyLabel.Location = new System.Drawing.Point(X+width, Y); 
      AllergyLabel.Size = new System.Drawing.Size(75, 23); 
      AllergyLabel.AutoSize = true; 
      AllergyLabel.BorderStyle = BorderStyle.FixedSingle; 
      AllergyLabel.Dock = DockStyle.Fill; 
      this.Controls.Add(AllergyLabel); 
     }  
     InitializeComponent(); 
    } 
} 
+1

Verwenden Flowlayoutpanel https://msdn.microsoft.com/en-us/library/system.windows.forms. flowlayoutpanel (v = vs.110) .aspx –

Antwort

0

Sie müssen X-Wert am Ende jeder Schleife aktualisieren:

public partial class AllergyBar : Panel 
{ 
    public AllergyBar(): base() 
    { 
     InitializeComponent(); 
    } 

    int X = 0, Y=0; 

    int height, width; 
    public AllergyBar(List<String> lstAlerts): base() 
    { 
     InitializeComponent(); 
     this.BackColor = System.Drawing.Color.WhiteSmoke; 
     this.Name = "panel2"; 
     this.Size = new System.Drawing.Size(75, 23); 
     this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; 
     foreach (string alert in lstAlerts) 
     { 
      Label AllergyLabel = new Label(); 
      AllergyLabel.Text = alert; 
      AllergyLabel.Location = new System.Drawing.Point(X, Y); 
      AllergyLabel.AutoSize = true; 
      AllergyLabel.BorderStyle = BorderStyle.FixedSingle; 
      AllergyLabel.Dock = DockStyle.Fill; 
      X += AllergyLabel.Width; 
      this.Controls.Add(AllergyLabel); 
     } 
    } 
}