The new textbox object does not have yet a parent, therefore txb.Parent.BackColor does not work.
Try to remove the originalBackColor member. In Txb_LostFocus you can do this: txb.BackColor = txb.Parent.BackColor, or use another appropriate colour.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello ,
i recently asked a question in https://learn.microsoft.com/en-us/answers/questions/1406472/textbox-as-textboxcolumn
and @gekka suggested a solution which works . I had modified some part of it according to my requirement but after cleaning and rebuilding multiple times it can not be drop from the toolbar to the form . i am not from the visual studio design . Am i missing something or it is a bug . Please help .
modifications are
namespace Pankajtripathi
{
public partial class CustomTextBox : TextBox
{
private int maxCharacters;
public int MaxCharacters
{
get { return maxCharacters; }
set
{
maxCharacters = value;
Text = Text.Length > maxCharacters ? Text.Substring(0, maxCharacters) : Text;
}
}
public CustomTextBox()
{
CustomTextBoxWork.AttachKeyEvent(this);
}
}
class CustomTextBoxWork
{
private static Color originalBackColor;
public static void AttachKeyEvent(TextBox txb)
{
txb.KeyDown += Txb_KeyDown;
txb.LostFocus += Txb_LostFocus;
originalBackColor = txb.Parent.BackColor; // Set the originalBackColor to the parent's back color
}
private static void Txb_KeyDown(object sender, KeyEventArgs e)
{
var txb = (TextBox)sender;
if (e.KeyCode == Keys.Escape)
{
txb.Text = "";
}
else if (e.KeyCode == Keys.Enter)
{
txb.BackColor = Color.Yellow; // Change the back color to a different color when Enter is pressed
Control ctl = txb;
while (ctl.Parent != null)
{
var next = ctl.Parent.GetNextControl(ctl, true);
if (next != null)
{
next.Focus();
e.SuppressKeyPress = true;
e.Handled = true;
return;
}
ctl = ctl.Parent;
}
}
}
private static void Txb_LostFocus(object sender, EventArgs e)
{
var txb = (TextBox)sender;
txb.BackColor = originalBackColor; // Revert back to the original back color (parent's back color) when focus is lost
}
}
}
The new textbox object does not have yet a parent, therefore txb.Parent.BackColor does not work.
Try to remove the originalBackColor member. In Txb_LostFocus you can do this: txb.BackColor = txb.Parent.BackColor, or use another appropriate colour.