自定义文本框甚至没有 运行

Custom Textbox Even not running

我为一个程序编写了一个自定义文本框,该程序旨在为我提供数据库值而无需大量转换或检查并具有自定义文本输入。它有几种不同的模式,例如自动格式化日期框和 SSN。它在 VB.NET 中运行良好,但现在我正在学习 C# 并且正在用 C# 重新制作程序进行练习,我在转换时遇到了障碍。 None 个事件将触发。

using System;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

public class DBTextBox : TextBox {
    private void InitializeComponent() {
            SuspendLayout();
            Enter += new EventHandler(DBTextBox_Enter);
            KeyPress += new KeyPressEventHandler(On_Key_Press);
            KeyUp += new KeyEventHandler(On_Key_Up);
            Leave += new EventHandler(Control_Leave);
            ResumeLayout(false);
    }

    public enum StyleTypes {
        DateBox,
        SSNBox,
        PhoneBox,
        TextBox,
        IntegerBox,
        DecimalBox
    }

    private StyleTypes Type { get; set; }
    public StyleTypes StyleType {
        get { return Type; }
        set { Type = value; }
    }

    private string _Default_Value { get; set; }
    public string Default_Value {
        get { return _Default_Value; }
        set { _Default_Value = value; }
    }

    private bool _AutoUpperCase = false;
    public bool AutoUpperCase {
        get { return _AutoUpperCase; }
        set { _AutoUpperCase = value; }
    }

    private bool _AutoUpperCaseFirstCharOnly = false;
    public bool AutoUpperCaseFirstCharOnly {
        get { return _AutoUpperCaseFirstCharOnly; }
        set { _AutoUpperCaseFirstCharOnly = value; }
    }

    private void On_Key_Up(object sender, KeyEventArgs e) {
        if (e.KeyCode != Keys.Back) {
            if (Type == StyleTypes.DateBox) {
                if (TextLength == 2 && Text.Contains("//") == false) {
                    Text = Text + "/";
                    SelectionStart = Text.Length + 1;
                }
                if (TextLength == 4 && Text.Substring(1, 1) == "//" && Text.Substring(3, 1) != "//" && CharCount('/') <= 1) {
                    Text = Text + "/";
                    SelectionStart = Text.Length + 1;
                }
                if (TextLength == 5 && Text.Substring(2, 1) == "//" && CharCount('/') <= 1) {
                    Text = Text + "/";
                    SelectionStart = Text.Length + 1;
                }
                if (Text.Contains("//")) {
                    Text = Text.Replace(@"//", @"/");
                    SelectionStart = Text.Length + 1;
                }
            }
            if (Type == StyleTypes.SSNBox) {
                MaxLength = 11;
                if (TextLength == 3 || TextLength == 6) {
                    Text = Text + "-";
                    SelectionStart = Text.Length + 1;
                }
            }
            if (Type == StyleTypes.PhoneBox) {
                MaxLength = 14;
                if (TextLength == 3 && Text.Contains('(') == false) {
                    Text = "(" + Text + ") ";
                    SelectionStart = Text.Length + 1;
                }
                if (TextLength == 9) {
                    Text = Text + "-";
                    SelectionStart = Text.Length + 1;
                }
            }
        }
    }

    private void Control_Leave(object sender, EventArgs e) {
        if (Type == StyleTypes.DateBox) {
            if (DateTime.TryParse(Text, out DateTime i)) {
                BackColor = Color.FromKnownColor(KnownColor.Window);
                Text = Convert.ToDateTime(Text).ToShortDateString();
            } else if (string.IsNullOrWhiteSpace(Text)) {
                BackColor = Color.FromKnownColor(KnownColor.Window);
                Text = string.Empty;
            } else {
                BackColor = Color.Salmon;
            }
        }
    }

    private void On_Key_Press(object sender, KeyPressEventArgs e) {
        if (Type == StyleTypes.DateBox) {
            if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false) {
                if (e.KeyChar == '/' && CharCount('/') <= 1) { } else { e.Handled = true; }
            }
        }
        if (Type == StyleTypes.PhoneBox) {
            if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false && e.KeyChar != '-' && e.KeyChar != '(' && e.KeyChar != ' ') {
                e.Handled = true;
            }
        }
        if (Type == StyleTypes.SSNBox) {
            if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false && e.KeyChar != '-') {
                e.Handled = true;
            }
        }
        if (Type == StyleTypes.DecimalBox) {
            if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false) {
                if ((e.KeyChar == '.' && CharCount('.') < 1) || (e.KeyChar == '-' && CharCount('-') < 1)) { } else { e.Handled = true; }
            }
        }
        if (Type == StyleTypes.IntegerBox) {
            if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false) {
                e.Handled = true;
            }
        }
    }

    private int CharCount(char Character) {
        char[] Chars = Text.ToCharArray();
        int Count = 0;
        foreach (var Item in Chars) {
            if (Item == Character) {
                Count += 1;
            }
        }
        return Count;
    }

    [Description("The Text in the box, returns null if Empty or White spaces")]
    public string DBText {
        get { if (string.IsNullOrWhiteSpace(Text)) { return null; } else { return Text; } }
        set { if (string.IsNullOrWhiteSpace(value)) { Text = null; } else { Text = value; } }
    }

    [Description("The returned Date if the Text is a date.")]
    public DateTime? DBDate {
        get { if (DateTime.TryParse(Text, out DateTime i)) { return Convert.ToDateTime(Text); } else { return null; } }
        set { Convert.ToDateTime(value).ToShortDateString(); }
    }

    public decimal? DBDecimal {
        get { if (decimal.TryParse(Text, out decimal i)) { return Convert.ToDecimal(Text); } else { return null; } }
        set { Text = value.ToString(); }
    }

    public int? DBInt {
        get { if (int.TryParse(Text, out int i) && Convert.ToInt32(Text) > int.MinValue && Convert.ToInt32(Text) < int.MaxValue) { return Convert.ToInt32(Text); } else { return null; } }
        set { Text = value.ToString(); }
    }

    public short? DBShort {
        get { if (short.TryParse(Text, out short i)) { return Convert.ToInt16(Text); } else { return null; } }
        set { Text = value.ToString(); }
    }

    private string UppercaseFirstLetter(string Input) {
        if (string.IsNullOrEmpty(Input)) { return Input; }
        char[] array = Input.ToCharArray();
        array[0] = char.ToUpper(array[0]);
        bool UpperCaseNextLetter = true;
        int LastCharPos = array.Count() - 1;
        if (_AutoUpperCaseFirstCharOnly) { LastCharPos = 1; }
        for (int i = 0; i <= LastCharPos; i++) {
            if (UpperCaseNextLetter == true) {
                array[i] = char.ToUpper(array[i]);
                UpperCaseNextLetter = false;
            } else {
                array[i] = char.ToLower(array[i]);
            }
            if (array[i] == ' ') {
                UpperCaseNextLetter = true;
            }
        }
        return new string(array);
    }

    private void DBTextBox_Enter(object sender, EventArgs e) {
        if (Type == StyleTypes.DateBox) {
            if (DateTime.TryParse(Text, out DateTime i)) {
                SelectionStart = 0;
                SelectionLength = Text.Length;
            }
        }
        if (Type == StyleTypes.TextBox && Text.Length > 0 && _Default_Value.Length > 0) {
            if (Text == _Default_Value) {
                SelectionStart = 0;
                SelectionLength = Text.Length;
            }
        }
    }
}

我需要做什么才能触发事件?

编辑:在我创建的用于测试它的调试表单上;

partial class frmDebug {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing) {
        if (disposing && (components != null)) {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent() {
            this.txtDate = new DBTextBox();
            this.cmdSet = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // txtDate
            // 
            this.txtDate.AutoUpperCase = false;
            this.txtDate.AutoUpperCaseFirstCharOnly = false;
            this.txtDate.DBDate = null;
            this.txtDate.DBDecimal = null;
            this.txtDate.DBInt = null;
            this.txtDate.DBShort = null;
            this.txtDate.DBText = null;
            this.txtDate.Default_Value = null;
            this.txtDate.Location = new System.Drawing.Point(72, 52);
            this.txtDate.Name = "txtDate";
            this.txtDate.Size = new System.Drawing.Size(100, 20);
            this.txtDate.StyleType = DBTextBox.StyleTypes.DateBox;
            this.txtDate.TabIndex = 0;
            // 
            // cmdSet
            // 
            this.cmdSet.Location = new System.Drawing.Point(68, 128);
            this.cmdSet.Name = "cmdSet";
            this.cmdSet.Size = new System.Drawing.Size(75, 23);
            this.cmdSet.TabIndex = 1;
            this.cmdSet.Text = "Set";
            this.cmdSet.UseVisualStyleBackColor = true;
            this.cmdSet.Click += new System.EventHandler(this.cmdSet_Click);
            // 
            // frmDebug
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.cmdSet);
            this.Controls.Add(this.txtDate);
            this.Name = "frmDebug";
            this.Text = "frmDebug";
            this.ResumeLayout(false);
            this.PerformLayout();

    }

    #endregion
    private System.Windows.Forms.Button cmdSet;
    public DBTextBox txtDate;
}

我的表单上没有任何代码,所以这就是它的样子;

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;

public partial class frmDebug : Form {
    public frmDebug() {
        InitializeComponent();
    }
}

LarsTech 有一个更好更正确的解决方案:

You don't call InitializeComponent from inside the TextBox. But a class doesn't have to listen to their own events. Use the overrides instead, example: protected override void OnKeyUp(KeyEventArgs e) {...}

我原来的回答:

看起来您可能只需要为 DBTextBox class 添加一个构造函数,它将调用您的私有 InitializeComponent() 方法。它应该看起来像这样:

public DBTextBox()
{
    InitializeComponent();
}