动态添加进度条代替按钮

时间:2017-09-04 09:30:35

标签: c#

我有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?
    }

1 个答案:

答案 0 :(得分:1)

如果所有内容都需要动态,那么您可以使用Button获取.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;
}