简体   繁体   中英

How do I use the UserControl?

  1. Developer Environment

    • Tools : Visual Studio 2017
    • Language: C# - Windows Form
  2. Create UserControl

    • testNext Property is Generic Type

    // ------- testControl.Designer.cs --------------------------------------

     partial class testTextBox<T> { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // textBox1 this.textBox1.Location = new System.Drawing.Point(3, 2); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(147, 21); this.textBox1.TabIndex = 1; this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.testTextBox_KeyPress); // testTextBox this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.textBox1); this.Margin = new System.Windows.Forms.Padding(0); this.Name = "testTextBox"; this.Size = new System.Drawing.Size(157, 26); this.Resize += new System.EventHandler(this.testTextBox_Resize); this.ResumeLayout(false); this.PerformLayout(); } private System.Windows.Forms.TextBox textBox1; } 

    // ------- testControl.cs ----------------------------------------------------

     public partial class testTextBox<T> : UserControl { public delegate void DelegateKeyPress(object sender, KeyPressEventArgs e); public event DelegateKeyPress testKeyPress; public testTextBox() { InitializeComponent(); } public T _testNext; // Generic property public T testNext { get { return this._testNext; } set { this._testNext = value; } } private void testTextBox_KeyPress(object sender, KeyPressEventArgs e) { if (this._testNext != null) { MessageBox.Show(this._testNext.GetType().Name); } if (this.testKeyPress != null) { this.testKeyPress(sender, e); } } } 
  3. Using testTextBox

    • I want to use testTextBox in a form, but I can not use it in Design Mode How do I use the testTextBox?

1.Make sure usercontrol and mainform have same namespace.

  1. Build Solution

  2. Double Click testControl.cs for open Design window.

  3. Go to toolbox, and find ** Comopnets ( ** is your project name )

  4. your usercontrol is in there. just add and use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM