Reputation: 133
I am supposed to change the position of three labels (ex: label1
is going to be in label2
's position) randomly every time I press a button.
So I decided to take the location of the labels and store them in an array. However, I don't know how to get a label's position. I tried saying double position = label1.location.X;
but it didn't work.
Upvotes: 2
Views: 21561
Reputation: 1642
get the values using
label1.Left, label1.Top
set the values using
label1.Location = new Point(x, y);
Do not forget to include
using System.Windows.Forms;
using System.Drawing; // to use System.Drawing.Point(Label.Left, Label.Top)
I've written the code that I hope should help you to get the idea. Click on the label to get its coordinates.
using System;
using System.Windows.Forms;
using System.Drawing;
class LabelForm : Form
{
Label label1;
//
public LabelForm()
{
label1 = new Label();
label1.Text = "ClickMe";
label1.Location = new Point(10, 10); // This is the place where you set the location of your label. Currently, it is set to 10, 10.
label1.Click += new EventHandler(labelClick);
Controls.Add(label1);
}
//
static void Main(string[] args)
{
LabelForm lf = new LabelForm();
Application.Run(lf);
}
//
protected void labelClick(object o, EventArgs e)
{
// This is how you can get label's positions
int left = label1.Left;
int top = label1.Top;
MessageBox.Show("Left position of the label: " + left
+ "\nTop position of the label: " + top,
"", MessageBoxButtons.OK);
}
}
Then just use randomizer to set the values to Point(x, y). Note, that you should also check the width and height of your window and subtract the width and height of your label not to go beyond window borders.
Upvotes: 3
Reputation: 9089
Label.Left, Label.Top
Location is just a Point struct that can't be modified.
Upvotes: 1
Reputation: 48076
You can access the Bounds
property, it's an object of type Rectangle
which has the width, height and x, y coordinates of the component.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.bounds(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.drawing.rectangle(v=vs.110).aspx
That is assuming you're working with the winform class Label
EDIT: A simpler property to use is Location
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.location(v=vs.110).aspx
If you just look at the msdn docs for Label
you'll find there are numerous ways to get that data.
Upvotes: 1