winform水平滚动条联动panel
需求:
滚动滚动条时显示pnlBack里面的button
文本框里输入数字,改变每行显示的按钮数
源码如下:
/// <summary> /// 窗体加载 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { InitialButtons(); } /// <summary> /// 往pnlBack中添加button并联动水平滚动条 /// </summary> /// <param name="a">每行显示的button数,默认为15</param> private void InitialButtons(int a = 15) { //初始化显示在pnlBack里面的button if (txtCols.Text.Trim() != "") { int.TryParse(txtCols.Text.Trim(), out a); if (a <= 0) { a = 15; } } pnlBack.Controls.Clear(); for (int i = 0; i < 60; i++) { Button btn = new Button(); btn.Size = new Size(140, 80); btn.Text = "Text" + (i + 1); if (i < a) { btn.Location = new Point(i * 140 + (i + 1) * 10, 10); } else if (i < 2 * a) { btn.Location = new Point((i - a) * 140 + (i + 1 - a) * 10, 100); } else if (i < 3 * a) { btn.Location = new Point((i - 2 * a) * 140 + (i + 1 - 2 * a) * 10, 190); } else { btn.Location = new Point((i - 3 * a) * 140 + (i + 1 - 3 * a) * 10, 280); } pnlBack.Controls.Add(btn); } pnlBack.Width = 10 + (10 + 140) * a; //初始化水平滚动条 Hsb.Maximum = pnlBack.Width + 20; Hsb.Minimum = 0; Hsb.LargeChange = pnlOwner.Width; Hsb.SmallChange = 5; } //水平滚动条滚动 private void Hsb_Scroll(object sender, ScrollEventArgs e) { pnlBack.Left = pnlBack.Left - (e.NewValue - e.OldValue); } //更改每行的按钮数目 private void btnOk_Click(object sender, EventArgs e) { InitialButtons(); }