2014-10-07 83 views
0

確定,所以我決定基於在陣列中的標籤進行控制以添加到面板上的Form_Load。下面是我的代碼,但無論通過按鈕偵聽器上傳多少個文件並重新加載此表單,它只顯示一個標籤,僅此而已。爲什麼只顯示一個?我添加了一個斷點,並證實計數也上升到2,3,等動態添加標籤僅示出一個

代碼:

public partial class Attachments : Form 
    { 
     ArrayList attachmentFiles; 
     ArrayList attachmentNames; 
     public Attachments(ArrayList attachments, ArrayList attachmentFileNames) 
     { 
      InitializeComponent(); 
      attachmentFiles = attachments; 
      attachmentNames = attachmentFileNames; 
     } 

     private void Attachments_Load(object sender, EventArgs e) 
     { 
      ScrollBar vScrollBar1 = new VScrollBar(); 
      vScrollBar1.Dock = DockStyle.Right; 
      vScrollBar1.Scroll += (sender2, e2) => { pnl_Attachments.VerticalScroll.Value = vScrollBar1.Value; }; 
      pnl_Attachments.Controls.Add(vScrollBar1); 
      Label fileName; 
      for (int i = 0; i < attachmentNames.Count; i++) 
      { 
       fileName = new Label(); 
       fileName.Text = attachmentNames[i].ToString(); 
       pnl_Attachments.Controls.Add(fileName); 
      } 
     } 

     private void btn_AddAttachment_Click(object sender, EventArgs e) 
     { 
      if (openFileDialog1.ShowDialog() == DialogResult.OK) 
      { 
       string fileName = openFileDialog1.FileName; 
       attachmentFiles.Add(fileName); 
       attachmentNames.Add(Path.GetFileName(fileName)); 
       this.Close(); 
      } 
     } 
    } 

回答

1

這是因爲標籤都堆疊在彼此的頂部。您需要爲每一個指定一個頂部或使用自動流程面板。

添加以下行創建新標籤將確保所有的標籤都可見後(您可能需要調整取決於您的字體乘數):

fileName.Top = (i + 1) * 22; 
0

由於competent_tech規定的標籤堆疊基礎但另一種方法是修改標籤的位置值。對此的好處是您可以控制標籤的絕對位置。

fileName.Location = new Point(x, y); 
y += marginAmount; 

x是窗體上的垂直位置,y是窗體上的水平位置。然後,所有必須修改的就是marginAmount變量中每個標籤之間的空間量。

在此

所以對於循環

for (int i = 0; i < attachmentNames.Count; i++) 
{ 
    fileName = new Label(); 
    fileName.Text = attachmentNames[i].ToString(); 
    pnl_Attachments.Controls.Add(fileName); 
} 

你可以將它修改爲這樣:

for (int i = 0; i < attachmentNames.Count; i++) 
{ 
    fileName = new Label(); 
    fileName.Text = attachmentNames[i].ToString(); 
    fileName.Location = new Point(x, y); 
    y += marginAmount; 
    pnl_Attachments.Controls.Add(fileName); 
} 

然後,所有你需要做的就是確定X,Y和marginAmount。