Setting a control

  • Thread starter Thread starter MFRASER
  • Start date Start date
M

MFRASER

I have a function that I can't seem to get to work properly. This function
is suppose to loop through a collection of controls and locate an existing
ojbect of that type. if it locates the control it uses that object if it
does not a new object is added.

public void SetMainControl(System.Windows.Forms.Control Testcontrol)

{

System.Windows.Forms.Control aTmpControl = TestControl;

bool found = false;

foreach(System.Windows.Forms.Control aControl in
StudyViewer_Fill_Panel.Controls)

{

if (aControl is aTmpControl)

{

found = true;

TestControl = aControl;

break;

}

}

if (!found)

{


StudyViewer_Fill_Panel.Controls.Add(Testcontrol);

}

Testcontrol.Dock = DockStyle.Fill;


}
 
I have a function that I can't seem to get to work properly. This function
is suppose to loop through a collection of controls and locate an existing
ojbect of that type. if it locates the control it uses that object if it
does not a new object is added.

An example:

public class MyControl : Control
{
// implementation of your control
}

private void Form1_Load(object sender, System.EventArgs e)
{
// add your control to the controls collection
this.Controls.Add(new MyControl());

// loop through all controls on the form and check if it's a
// MyControl
foreach (Control c in this.Controls)
{
// method 1
if (c.GetType() == typeof(MyControl))
{
// it's a MyControl
}

// method 2
if (c is MyControl)
{
// it's a MyControl
}

}

}
 
That is what I thought but when I create a function to set the control
and pass in that control the code will not compile.

So If I changed your code to

An example:

public class MyControl : Control
{
// implementation of your control
}

private void Form1_Load(object sender, System.EventArgs e)
{
// add your control to the controls collection
//this.Controls.Add(new MyControl());
this.SetMainControl( new MyControl());


}
private void SetMainControl(System.Windows.Forms MyControl)
{
// loop through all controls on the form and check if it's a
// MyControl
foreach (Control c in this.Controls)
{
// method 1
if (c.GetType() == typeof(MyControl))
{
// it's a MyControl
}

// method 2
if (c is MyControl)
{
// it's a MyControl
}

}

}
}
 
That is what I thought but when I create a function to set the control
and pass in that control the code will not compile.

That's beause the parameter has to be a Control, like this:

private void SetMainControl(Control MyControl)
...
 
Back
Top