Skip to content

Instantly share code, notes, and snippets.

@masaru-b-cl
Created May 1, 2012 14:08
Show Gist options
  • Save masaru-b-cl/2568139 to your computer and use it in GitHub Desktop.
Save masaru-b-cl/2568139 to your computer and use it in GitHub Desktop.
Validatedで値をゼロ埋めするコンポーネント試作
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class CodePaddingProvider : Component
{
public CodePaddingProvider()
{
InitializeComponent();
this.Disposed += OnDisposed;
}
public CodePaddingProvider(IContainer container)
{
container.Add(this);
InitializeComponent();
this.Disposed += OnDisposed;
}
private Control targetContainer;
public Control TargetContainer
{
get { return this.targetContainer; }
set
{
if (targetContainer == value) return;
if (targetContainer != null)
{
targetContainer.ControlAdded -= OnControlAdded;
}
targetContainer = value;
if (targetContainer != null)
{
targetContainer.ControlAdded += OnControlAdded;
}
}
}
private void OnControlAdded(object sender, ControlEventArgs e)
{
var textBox = e.Control as TextBox;
if (textBox == null) return;
textBox.Validated -= OnValidated;
textBox.Validated += OnValidated;
}
private void OnValidated(object sender, EventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
var current = textBox.Text;
if (String.IsNullOrEmpty(current)) return;
var result = current.PadLeft(10, '0');
textBox.Text = result;
}
private void OnDisposed(object sender, EventArgs e)
{
this.targetContainer = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment