List of Exercises

Scrollbar Control in WinForms C#

	    
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Scrollbar_Position
{
  public partial class Form1 : Form
  {
    int i = 0;
    public Form1()
    {
      InitializeComponent();
      vScrollBar1.Value = panel1.VerticalScroll.Value;
      vScrollBar1.Minimum = panel1.VerticalScroll.Minimum;
      vScrollBar1.Maximum = panel1.VerticalScroll.Maximum;
      vScrollBar1.Scroll += vScrollBar1_Scroll;

      panel1.ControlAdded += panel1_ControlAdded;
      panel1.ControlRemoved += panel1_ControlRemoved;
     
      textBox1.Multiline = true;
      textBox1.Height = 60;
      vScrollBar1.Enabled = false;
    }

    void panel1_ControlRemoved(object sender, ControlEventArgs e)
    {
      vScrollBar1.Minimum = panel1.VerticalScroll.Minimum;
    }

    void panel1_ControlAdded(object sender, ControlEventArgs e)
    {
      vScrollBar1.Minimum = panel1.VerticalScroll.Minimum;
    }

    private void Add_Control_Click(object sender, EventArgs e)
    {
      i++;
      Button btn = new Button();
      btn.Text = "button" + i.ToString();
      btn.Location = new Point(10, i * 30);
      panel1.Controls.Add(btn);

      textBox1.Text += "button" + i.ToString() + Environment.NewLine;
      if (!vScrollBar1.Enabled)
        vScrollBar1.Enabled = true;
    }

    private void Remove_Control_Click(object sender, EventArgs e)
    {
      panel1.Controls.Clear();
      textBox1.Text = "";
      i = 0;
      vScrollBar1.Value = panel1.VerticalScroll.Value;
      vScrollBar1.Enabled = false;
    }

    private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
    {
      panel1.VerticalScroll.Value = vScrollBar1.Value;
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
      textBox1.ScrollBars = ScrollBars.Vertical;
    }
  }
}

		
	 


Download the project of Visual Studio 2013 in DropBox Download


How to Use ScrollBar Control for Panels and TextBoxes in Winforms C#


Video Thumbnail