A problem with Custom Controls

  • Thread starter Thread starter Dom
  • Start date Start date
D

Dom

I've created a Custom Control -- essentially, I've beefed up the
DataGridView Control. One property is "ColumnForComment", and this
value must be between 0 and the total number of columns. So the Set
looks like this:


int m_ColumnForComment = -1;

public int ColumnForComment
set
{
if (value < 0) return;
if (value >= base.Columns.Count) return;
...
}

Now, when I include this control into a form, the designer for that
form has a line:

<control>.ColumnForComment = 5;

But it puts that line before the line that creates the columns ... so
the set sees that "value" is less that base.Columns.Count and does not
get executed.

Of course, I just moved the line to a better place, but every time I
make a simple change to the custom control, it moves it back again.
Is there a better way to handle this?

Dom
 
[...]
Now, when I include this control into a form, the designer for that
form has a line:
<control>.ColumnForComment = 5;
But it puts that line before the line that creates the columns ... so
the set sees that "value" is less that base.Columns.Count and does not
get executed.
Of course, I just moved the line to a better place, but every time I
make a simple change to the custom control, it moves it back again.
Is there a better way to handle this?

I can think of at least three possible approaches:

     -- Don't allow the property to be set in the Designer.  Require client  
code to set it after the object has been constructed, to ensure that the  
number of columns is valid.

     -- Don't do range checking at this point.  Instead, validatethe value  
when you actually have to use it and throw an exception if it's out of  
range then.

     -- Don't do range checking at this point.  Instead, allow whatever  
theoretically valid value the client code sets, and then when you need to 
use the value, pin the value to a valid range based on the number of  
columns (i.e. if the value is greater than the maximum column index, just 
use the maximum column index instead of the set value).

I would personally prefer the last suggestion.  Since the column count can  
change after construction, you simply have no reliable way to ensure when 
the property is set that it will be a valid value when it's used.  And in  
this scenario, it seems "nicer" to try to do something reasonable with the  
out-of-range value than to throw an exception.

Pete

Thanks for the suggestions. I'll take the last approach. The first
is out of the question, since it has to be set in the designer.
 
Back
Top