I wanted to create subclass of the textbox so that I can add behaviour that I want in it. I first tried visual route by adding item to the project, choosing common controls and draging txtbox from toolbox to design view. But this gave me the error when I tried to drag that new class to the form from the toolbox "Failed to load toolbox item". So I tried to create subclass in code. I created new cs file ZControls to include all future subclassed controls and created new txtbox class in it and added some code to change the behaviour when user presses Enter.
class Ztextbox : TextBox
{
private void keypressed(Object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
this.SelectNextControl((Control) sender, true, true, true, true);
}
}
}
It worked and the new Ztxtbox control was in the toolbox and I successfuly placed it on the form. But it didn't change the behaviour, when I press Enter nothing happens. So I guess the code that I could not include might be the culprit
TextBox tb = new TextBox();
this.Controls.Add(tb);
tb.KeyPress += new KeyPressEventHandler(keypressed);
but in this example the textbox is created in the form class it isn't dragged as I did, and it is not subclassed in its own cs file. How do I get this to work?
Ok I get it working but not with my method keypressed. I did it through design view where I clicked the ZtextBox and pressed Enter in its KeyPress event so the IDE created new event for KeyPress where I placed my code and it worked. The code for overriding KeyPressEvent was automaticaly added in forms InitializeComponent() method:
this.txtUsername.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtUsername_KeyPress);
I tried to insert my method in above EventHandler but the error was "The name -keypressed- does not exist in current context".
So this is not really good solution only workaround.
Any help?