Kasper Hansen Kasper Hansen - 1 year ago 138
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 =

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?


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


Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download