adding control programmatically

  • Thread starter Thread starter johnmmcparland
  • Start date Start date
J

johnmmcparland

am trying to add controls (e.g. radio buttons, group boxes) to a
windows form in a method which I call from the constructor.

However, when I do things like;

RadioButton rb= new RadioButton();
....
rb.Location.X= 67;

this.Controls.Add(rb); // this is the Windows Form instance

I am told that;

"Cannot modify the return value of
'System.Window.Forms.Control.Locatoin' because it is not a variable"

I have tried to use CreateControl() but it doesn't seem to have any
effect.

If anyone knows how to do this please help asap

John
 
John,

The reason that this doesn't work is because Location is of type Point,
which is a value type. When you return value types from properties or
methods (through the return value, not ref parameters), a copy is made and
returned to you.

That being said, when you do this:

rb.Location.X= 67;

You are setting the X property/field on a copy returned to you. To
perform this operation, you would need to do this:

// Store the location.
Point temp = rb.Location;

// Set the X value.
temp.X = 67;

// Set the location back.
rb.Location = temp;

Hope this helps.
 
Hi,


Additionaly to Nicholas comment you can use Left to set a new position.

cheers,
 
The Location property is of type System.Drawing.Point (a struct). This
means that accessing the button's Location property returns a copy of
the struct, and since this is not assigned to a variable it cannot be
modified. (Even if the compiler let this through you would still have
been modifying a temporary variable, and it would have no effect on the
button).

Instead, use

rb.Location = new Point(x, y);

Jon.
 
[reply to all]

thanks all for your help. I went for the option Nicholas posted. It's
got past the compiler and it's now up to me to make sure my algorithm
is right.

Thanks again all

John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top