0

I have a list of controls and their locations in a datatable and I would like to go through the whole datatable and set the location of each control. The difficulty I have is defining which control I want to set the location for. For example one can set the location of a control as follows:

button1.Location = new Point(xpos, Ypos);
button2.Location = new Point(xpos, Ypos);

The thing is that I can't hard code the names of all the controls before hand. This is the code that I currently use: The datatable contains one row for every control in the form, and has three columns: the control name, the x location and the y location.

int rowPosition = 0;
Control x;
string controlName;
int xCoord;
int yCoord;

foreach (DataRow row in dtControlPosition.Rows)
{                
    controlName = dtControlPosition.Rows[rowPosition]["Control"].ToString();

    xCoord = Convert.ToInt32(dtControlPosition.Rows[rowPosition]["XCoord"].ToString());

    yCoord = Convert.ToInt32(dtControlPosition.Rows[rowPosition]["YCoord"].ToString());

    // don't have any idea what to do here:
    // I tried x.Name = controlName
    // x.Location = new Point(Convert.ToInt32(xCoord),Convert.toInt32(yCoord));

    rowPosition = rowPosition +1;
} 

When I try the above I receive an error "use of unassigned local variable "x"."

stuartd
  • 70,509
  • 14
  • 132
  • 163
Tom
  • 527
  • 1
  • 8
  • 28
  • possible duplicate of [Why compile error "Use of unassigned local variable"?](http://stackoverflow.com/questions/9233000/why-compile-error-use-of-unassigned-local-variable) – xxbbcc Jul 30 '15 at 16:21
  • you created a variable like Control x; but you did not initialize it. – sm.abdullah Jul 30 '15 at 16:22

1 Answers1

1

Assuming the controls already exist on the form and you just want to set the location, call Form.ControlCollection.Find to get a reference to the control from its name:

Searches for controls by their Name property and builds an array of all the controls that match

So, something like this:

Control x = this.Controls.Find(controlName, true).FirstOrDefault();

if (x != null)  
    x.Location = new Point(xCoord, yCoord);           
stuartd
  • 70,509
  • 14
  • 132
  • 163