Posted 16 July 2026, 9:29 pm EST
I am implementing a feature that embeds my UserControl inside a ToolStripControlHost.
My UserControl contains a C1TextBox control. However, when the textbox loses focus, a null reference exception occurs.
The root cause is that when the control is hosted inside a ToolStripControlHost,
FindForm() cannot locate a parent Form and returns null.
The following code is causing the issue:
protected override void OnValidating(CancelEventArgs e)
{
if (this.ef)
return;
object dr = this.dr;
if (!e.Cancel && this.cs && this.dl && (!0.Equals(this.dr) || !(base.Text == "-")) && !this.UpdateValueWithCurrentText())
{
this.gh = true;
e.Cancel = true;
}
bool cancel = e.Cancel;
base.OnValidating(e);
bool flag = false;
object parsedValue = this.Value;
ErrorInfo errorInfo = this.ErrorInfo.a();
if (e.Cancel && !cancel)
flag = this.CheckValidationResult(ErrorReasonEnum.PreValidationError, ref parsedValue, errorInfo);
if (!e.Cancel)
return;
if (errorInfo.CanLoseFocus)
{
e.Cancel = !flag;
this.Value = parsedValue;
}
this.dr = dr;
this.dv = false;
Form form = this.FindForm();
C1TextBox activeControl = form.ActiveControl as C1TextBox;
if (form == null || activeControl == null || !activeControl.cs || activeControl == this)
return;
activeControl.ai();
}
As you can see, the problematic section is:
Form form = this.FindForm();
C1TextBox activeControl = form.ActiveControl as C1TextBox;
if (form == null || activeControl == null || !activeControl.cs || activeControl == this)
return;
The code attempts to access
form.ActiveControl before checking whether form is null. When the control is hosted inside a ToolStripControlHost, FindForm() may return null, resulting in a null reference exception before the null check is reached.
