Visual Studio 2005 and the Load method of UserControl

Posted by on Comments (0)

Maybe you already met this kind of problems with UserControl and Visual Studio 2005 : you design a main winform without any problems, you design a user control without any problem. But then when you add the user control to the main form, the designer will encouter an error on the main form. You nevertheless may run the application without any problem.

The reason for this is that the designer is calling the load method of user controls when you open the form that is hosting those user controls.

 

A simple test :

Here is the designer part of my user control (an empty one with just one label, this is enough to demonstrate our problem):


Here is the code behind :



The important thing there is the Load method.

 

Then, if I want to add the user control to a main empty form, here is what you will see :

Most of the time, this is not annoying, but sometimes, this may lead to the impossibility to woon the main form with the designer (because you are in design time and not run time, information may not be available):

 


You can then work with the DesignTime property of the user control :

 

Posted in: .NET 2.0 | Visual Studio 2005   Tags:

Attribute, bitwise operations and enumerations : the FontStyle example

Posted by on Comments (1)

Recently, one of my clients was borred about a customisation of a .NET 2.0 RichTextBox control.

He was using a ToolStrip to change the style of text selections :

The problem he met was about the toggling between the different styles.

If you take a look at the FontStyle enumeration, you'll see that it "has a FlagsAttribute attribute that allows a bitwise combination of its member values" (cfr MSDN).

Knowing that, the values correlated to the different FontStyle are :

  • Regular : 0 (binary representation : 0000)
  • Bold : 1 (binary representation : 0001)
  • Italic : 2 (binary representation : 0010)
  • Underline : 4 (binary representation : 0100)
  • Strikeout : 8 (binary representation : 1000)

The fact that enumeration constants are defined in power of 2 is of required by the FlagsAttribute to avoid overlaps of different combinations.

Imagine that the selected text in the RichTextBox is bold and underlined. You'll get a FontStyle constant of 5 (binary representation : 0101).

If you ask to remove the bold style, you'll then just have to apply a XOR operator :

0101 XOR 0001 = 0100

If you then want to toggle again :

0100 XOR 0001 = 0101

The code in C# will thus be something like (rtb is the reference to the RichTextBox):

Font f = new Font(this.rtb.Font.FontFamily, this.rtb.Font.Size, this.rtb.SelectionFont.Style ^ FontStyle.Bold);
this.rtb.SelectionFont = f;

Easy, isn't it? :)

This will of course apply to all the enumeration types that have the FlagsAttribute.

Posted in: .NET 2.0   Tags: