Kasper Hansen Kasper Hansen - 1 month ago 19
C# Question

Cannot get TypeConverter.ConvertFromString to work with a Rectangle

The following code is taken from a measureup test for the 70-536 Microsoft .NET exam.

private void frmMain_Paint(object sender, PaintEventArgs e)
{
System.ComponentModel.TypeConverter rectConverter =
System.ComponentModel.TypeDescriptor.GetConverter(typeof(Rectangle));

Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50,50,200,200"); //fails
e.Graphics.DrawRectangle(Pens.Black, rect);
rect.Inflate(-10, -10);
e.Graphics.DrawRectangle(Pens.Blue, rect);
}


But the line

Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50,50,200,200");


fails with "50,50,200,200" is not a valid value for Int32". I am not familiar with the TypeConverter class at all. But according to the explanation, this was supposed to draw a black rectangle at the coordinate (50,50) with the size (200,200). Then draw a new smaller blue rectangle inside the black one by using the Inflate method. But why does ConvertFromString fail?

edit:

I guess this is the .NET implementation of the ConvertFromString method regarding the Rectangle class:

http://www.dotnetframework.org/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/fx/src/CommonUI/System/Drawing/RectangleConverter@cs/1/RectangleConverter@cs

Answer

Yeah, I can't reproduce it, but don't get stuck on that minor detail, looks like you're trying to figure out a bigger problem than that, just make the rectangle work and return to this later if it keeps bugging you. Something like this should work..

rect.Height = 200;
rect.Width = 200;
rect.PointToScreen(new Point(50, 50));
Comments