问题
I have 25 panel control (Visible false). I want to make it visible.
But it doesn' work: (Error 1 'string' does not contain a definition for 'Visible' and no extension method 'Visible' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) )
for (int i = 0; i < 25; i++)
{
string panelID = "panel" + i.ToString();
panelID.Visible = true;
}
Help
回答1:
Your code is wrong in so many fronts.
As it is, what you're doing is creating 25 strings with values panel0
, panel1
, panel2
etc., and trying to assign a value to a property of it. But strings don't contain a property named Visible
, so obviously you'll get an error.
What you want to do is get hold of controls of type Panel
in your form, and set their values.
foreach(var panel in this.Controls.OfType<Panel>())
{
panel.Visible = true;
}
Caveat: the above will only find Panel
controls in your topmost form. If there are controls that are nested, you'd want to perhaps write a method to recursively find them. Above is just to give you the idea.
In addition, if you have multiple Panel
controls and if you only want to set the property of those panels names fit your naming convention you can filter them out.
foreach(var panel in this.Controls.OfType<Panel>())
{
if( panel name fits your naming convention)
panel.Visible = true;
}
Here, you can look for correct panel name by using a Regex
, use a custom function etc.
回答2:
You can store all the dynamically created Panels to a collection from which you can refer them by their Name. One such collection is Dictionary.
public class Form1 : Form
{
Dictionary<string, Panel> panels = new Dictionary< string, Panel>();
public void Form1_Load(object sender, EventArgs e)
{
for (var i = 0; i < 25; I++)
{
Panel panel = new Panel();
panel.Name = "panel" + i.ToString();
this.Controls.Add(panel);
panels.Add(panel.Name, Panel);
}
}
}
now you can make them visible /invisible as following.
private void ShowHidePanel(int panelNumber, bool visible)
{
panels["panel"+panelNumber.ToString()].Visible = visible ;
}
or if you want to show or hide all the panels you can do as following.
private void ShowHidePanels(bool visible)
{
for (var i = 0; i < 25; i++)
{
panels["panel" + i.ToString()].Visible = visible;
}
}
来源:https://stackoverflow.com/questions/46332748/panel-control-with-variable-name