2013-06-03 103 views
20

在Windows窗體中,我可以通過這樣動態地添加控制:添加控件動態在FlowLayoutPanel的

for (int i = 0; i < 5; i++) 
{ 
    Button button = new Button(); 
    button.Location = new Point(160, 30 * i + 10); 

    button.Tag = i; 
    this.Controls.Add(button); 
} 

如何添加控件動態的FlowLayoutPanel

回答

31

對於FlowLayoutPanel,由於控件是爲您安排的,因此不需要指定位置。只要改變「flowLayoutPanel1」你FlowLayoutPanel名稱:

for (int i = 0; i < 5; i++) 
{ 
    Button button = new Button(); 
    button.Tag = i; 
    flowLayoutPanel1.Controls.Add(button); 
} 
-4

使項目從數據庫(SQL Server)的動態流向flowLayoutPanel1:究竟是什麼

void button1_Enter(object sender, EventArgs e) 
    { 
     Button btn = sender as Button; 
     btn.BackColor = Color.Gold; 
    } 

void button1_Leave(object sender, EventArgs e) 
    { 
     Button btn = sender as Button; 
     btn.BackColor = Color.Green; 
    } 


private void form1_Load(object sender, EventArgs e) 
    { 
     flowLayoutPanel1.Controls.Clear(); 
     SqlConnection cn = new SqlConnection(@"server=.;database=MyDatabase;integrated security=true"); 

     SqlDataAdapter da = new SqlDataAdapter("select * from Items order by ItemsName", cn); 

     DataTable dt = new DataTable(); 
     da.Fill(dt); 

     for (int i = 0; i < dt.Rows.Count; i++) 
     { 
      Button btn = new Button(); 
      btn.Name = "btn" + dt.Rows[i][1]; 
      btn.Tag = dt.Rows[i][1]; 
      btn.Text = dt.Rows[i][2].ToString(); 
      btn.Font = new Font("Arial", 14f, FontStyle.Bold); 
      // btn.UseCompatibleTextRendering = true; 
      btn.BackColor = Color.Green; 
      btn.Height = 57; 
      btn.Width = 116; 
      btn.Click += button1_Click; // set any method 
      btn.Enter += button1_Enter; // 
      btn.Leave += button1_Leave; // 


      flowLayoutPanel1.Controls.Add(btn);     

     } 
+19

沒有SQL有這個問題呢? –

+2

幫助我,因爲我將控件從數據庫添加到表單 – Mark