开发者

Design time error in form for object with

I have an control that i开发者_如何学Gonherits from another control (TxTextControl). I have a SelectedText property that basicaly wraps the base SelectedText property, which is apparently needed because my control is implementing an interface with that property. The code is this:

public string SelectedText
{
  get
  {
    return base.Selection.Text; // Error here (#1042)
  }
  set
  {
    if (base.Selection == null)
    {
      base.Selection = new TXTextControl.Selection(0, 0);
    }
    base.Selection.Text = value;
  }
}

When I drop this control on a form, no problems. It compiles and runs. Everything looks great. However, when I save, close then reopen the form, the form designer shows this error:

Object reference not set to an instance of an object.

1. Hide Call Stack

at Test.FormattedTextBox2.get_SelectedText() in C:\Projects\Test\FormattedTextBox2.cs:line 1042

Anyone know what is going on? I'm about to pull out my last hair...

UPDATE:

darkassisin93's answer wasn't exactly correct, but that was because my posted code wasn't exactly accurate. I needed to test if base.Selection was null before attempting to access a property of that object. In any case, that answer got me headed in the right direction. Here is the actual solution:

public string SelectedText
{
  get
  {
    string selected = string.Empty;
    if (base.Selection != null)
    {
      selected = base.Selection.Text;
    }
    return selected; 
  }
  set
  {
    if (base.Selection == null)
    {
      base.Selection = new TXTextControl.Selection(0, 0);
      // Have to check here again..this apparently still 
      // results in a null in some cases.
      if (base.Selection == null) return;
    }
    base.Selection.Text = value;
  }
}


Try replacing

return base.SelectedText;

with

return base.SelectedText ?? string.Empty;

It's most likely because the base class's SelectedText property is set to null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜