Windows Forms: How to use a Custom control in C#

Create custom picture box with scrollbars in C# using custom control.

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "CustomControl" and then click OK

custom controlStep 2: Design your form as below

c# custom control

Step 3: Create a custom control, then modify your code as below

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 CustomControl
{
    public partial class MyPictureBox : Panel
    {
        PictureBox pictureBox;
        public MyPictureBox()
        {
            InitializeComponent();
            pictureBox = new PictureBox();
            this.Controls.Add(pictureBox);
        }

        [Category("Custom")]
        [Browsable(true)]
        [Description("Set path to image file")]
        [Editor(typeof(System.Windows.Forms.Design.WindowsFormsComponentEditor),typeof(System.Drawing.Design.UITypeEditor))]
        public string ImageFile
        {
            set
            {
                //Set image to picture box
                Image img = Image.FromFile(value);
                pictureBox.Image = img;
                pictureBox.Size = img.Size;
            }
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
        }
    }
}

Step 4: Add code to handle your form

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 CustomControl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            using(OpenFileDialog ofd=new OpenFileDialog() { Multiselect = false, ValidateNames = true, Filter = "JPEG|*.jpg" })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    txtFileName.Text = ofd.FileName;
                    myPictureBox1.ImageFile = ofd.FileName;
                }
            }
        }
    }
}

VIDEO TUTORIALS