Click here to Skip to main content
15,897,968 members
Articles / Desktop Programming / Windows Forms

How To Build Multi-control Components when Inheriting from an Existing Control (Intro and TextBox Example)

Rate me:
Please Sign up or sign in to vote.
4.53/5 (10 votes)
28 Oct 2008MIT5 min read 59.8K   590   45  
This article will get you started in building your own multi-control components without using the UserControl class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MultiCtrls
{
	public partial class LabeledTextBox : TextBox
	{
		public LabeledTextBox()
		{
			InitializeComponent();
		}
		protected Label _label = null; // our label
		protected string _LabelText = ""; // caption of our label
		protected int _offset = 5; // space between editbox and label
		public int offset
		{
			get { return _offset; }
			set
			{
				_offset = value;
				setControlsPosition();
			}
		}
		public string LabelText
		{
			get { return _LabelText; }
			set
			{
				_LabelText = value;
				setControlsPosition();
			}
		}
		protected virtual void setControlsPosition()
		{
			if (_label != null)
			{
				_label.Text = _LabelText;
				_label.AutoSize = true;
				_label.Left = this.Left - _label.Width - _offset;
				_label.Top = this.Top + 3;
			}
		}
		protected override void OnParentChanged(EventArgs e)
		{
			if (this.Parent != null)
			{
				_label = new Label();

				this.Parent.Controls.Add(_label);
				setControlsPosition();
			}
			base.OnParentChanged(e);
		}
		protected override void OnLocationChanged(EventArgs e)
		{
			setControlsPosition();
			base.OnLocationChanged(e);
		}
		protected override void Dispose(bool disposing)
		{
			if (_label != null)
				_label.Dispose();
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer Agilion Consulting
Poland Poland
I specialize at C#, developing Enterprise solutions. I have some knowledge of ASP.NET MVC - looking forward to use it together with Typescript.

Comments and Discussions