Karlos
Karlos

Reputation: 37

component which inherits from textbox control

I am trying to create a component which inherits controls from textbox control (Visual Studio 2017, Web Forms Application using C#).

I'm trying to make that textbox only could accept numerical values and if textbox has over 11 characters, theN them characters will be shown in red color.

I understand how to return a string from component class, but I don't really understand how to transfer method which changes the color to the main class where textbox is.

Component class part:

public partial class textbox : Component
   {
       public textbox()
       {
           InitializeComponent();
    }

    public textbox(IContainer container)
    {
        container.Add(this);

        InitializeComponent();
    }

//METHOD TO BE USED IN add_drivers
    public void textBox1_TextChanged(object sender, EventHandler e)
    {
        if (textBox1.MaxLength > 11)
        {
            textBox1.ForeColor = Color.Red;
        }

    }

add_driver class:

namespace Component
{
    public partial class add_driver : Form
    {
    public add_driver()
    {
        InitializeComponent();
    }

    private void add_driver_Load(object sender, EventArgs e)
    {

    }



    private void phoneNr_textbox_TextChanged(object sender, EventArgs e)
    {

  // IN THIS PART I'M NOT SURE HOW TO CALL METHOD FROM COMPONENT
    }

    private void phoneNr_textbox_KeyPress_1(object sender, KeyPressEventArgs e)
        {
        }
   }
    }

Upvotes: 0

Views: 542

Answers (1)

mmathis
mmathis

Reputation: 1610

You need to handle the KeyPress event in your textbox class, which should inherit from the existing TextBox class - otherwise you'll need to recreate all of the existing TextBox behavior! Also, note that standard casing for class and method names in C# is CamelCase, not snake_case or pascalCase.

public partial class MyTextBox : TextBox
{
   public MyTextBox()
   {
     InitializeComponent();
   }

  protected override void OnTextChanged(object sender, EventArgs e)
  {
     if (this.Text.Length > 11)
     {
       this.ForeColor = Color.Red;
     }
  }

  protected override void OnKeyPressed(object sender, KeyPressedEventArgs e)
  {
    // check for a number, set e.Handled to true if it's not a number
    // may need to handle copy-paste and other similar actions
  }
}

There may be some additional edge cases you need to handle, or some creature comforts you may wish to add to ease use of your new component (e.g., add a property to get the numeric value directly, rather than having the convert the Text property every time).

Given that you've added these methods to your MyTextBox class, you won't need event handlers for them in your AddDrivers form.

Upvotes: 1

Related Questions