2016-08-01 1 views
0

WindowsフォームPanelと番号Labelを使用してユーザーコントロールを作成しようとしていますが、テキストは水平方向にPanelに動的に追加されています。私は下のコードで試しており、Labelが無効になります。パネルとラベルを使用したユーザーコントロールの動的な追加

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

使用FlowLayoutPanel https://msdn.microsoft.com/en-us/library/system.windows.forms。 flowlayoutpanel(v = vs.110).aspx –

答えて

0

あなたは、各ループの最後でX値を更新する必要があります。

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); 
     } 
    } 
} 
関連する問題