2017-09-04 31 views
0

我有Windows窗体,我正在动态添加面板。在该面板中,我添加了按钮和一些标签。当用户点击按钮时,它应该从按钮切换到进度条。动态添加进度条代替按钮

Present scenario

Required result

Panel p = new Panel(); 
int x=20; 
int y=20; 
p.Location = new System.Drawing.Point(x, y); 
p.Size = new Size(682, 80); 
p.BackColor = System.Drawing.Color.LightCyan; 
Label l1 = new Label(); 
l1.Text =" Hello "; 
l1.AutoSize = true; 
l1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); 

    Label l2 = new Label(); 
    l2.Location = new System.Drawing.Point(20, 22); 
    l2.AutoSize = true; 
    l2.Text ="Description"; 

    Button b = new Button(); 
    b.Name = "UpdateButton"+i; 
    b.Text = "Update"; 
    b.Location = new System.Drawing.Point(551, 22); 
    b.Size = new Size(75, 23); 
    b.Click += new EventHandler(updateBtnClick); 
    p.Controls.Add(l4); 
    p.Controls.Add(l5); 
    p.Controls.Add(b); 

    ProgressBar pb = new ProgressBar(); 
    pb.Location = new System.Drawing.Point(551, 30); 
    pb.Size = new Size(125, 5); 
    p.Controls.Add(pb); 
    pb.Visible = false; 
    this.Controls.Add(p); 

    private void updateBtnClick(object sender, EventArgs e) 
    { 
     Button tempB = (Button)sender; 
     tempB.Visible = false; 
     //Need to add progress bar here. How to get object of progress bar? 
    } 
+0

因为我们不能告诉有多少面板会b在那里。 – Blessy

回答

1

如果一切都需要是动态的,那么你可以使用该按钮来获得.Parent,那么它的.Controls,并使用.OfType<ProgressBar>()从该集合获取第一ProgressBar ,像这里:

private void updateBtnClick(object sender, EventArgs e) 
{ 
    Button tempB = (Button)sender; 
    tempB.Visible = false; 

    ProgressBar pb = tempB.Parent.Controls.OfType<ProgressBar>().FirstOrDefault(); 
    if (pb != null) pb.Visible = true; 
}