试图通过不起作用的数组改变标签的颜色?

时间:2010-06-18 19:13:05

标签: c#

我正在尝试制作一个循环来检查某些文件是否存在,如果他们这样做,他们将在我的表单上更改指标标签,但我似乎无法解决如何执行此操作w /手动输入每一个,例如:

        if (File.Exists("C:\\MonitorFiles\\BOT-PC-8is1.txt"))
        {
            PC8IS1.BackColor = Color.Green;
        }
        if (File.Exists("C:\\MonitorFiles\\BOT-PC-8is2.txt"))
        {
            PC8IS2.BackColor = Color.Green;
        }
        if (File.Exists("C:\\MonitorFiles\\BOT-PC-8is3.txt"))
        {
            PC8IS3.BackColor = Color.Green;
        }

我已经尝试了几种非常基本的方法来构建数组并替换但我不能放“VariableX.backcolor”,我试过[变量] .backcolor,没有骰子。

这是一个很难在谷歌搜索,并希望有一个简单的答案!

由于

3 个答案:

答案 0 :(得分:2)

你想要的是一本字典,密钥将是文件名,该值将成为你的控制。

public partial class Form1 : Form
{
    Dictionary<string, Label> files;
    public Form1()
    { 
        InitializeComponent();
        files = new Dictionary<string,Label>();
        files.Add("C:\\MonitorFiles\\BOT-PC-8is1.txt", PC8IS1);
        files.Add("C:\\MonitorFiles\\BOT-PC-8is2.txt", PC8IS2);
        files.Add("C:\\MonitorFiles\\BOT-PC-8is3.txt", PC8IS3);
     }
    public void otherFunc()
    {
        foreach (var item in files)
        {
            if (File.Exists(item.Key))
                item.Value.BackColor = Color.Green;
        }
    }
}

答案 1 :(得分:1)

您也可以制作标签的数组(或列表):

private List<Label> labels = new List<Label> 
{ 
    PC8IS1, 
    PC8IS2,
    PC8IS3,
    // ...
};

然后,在你的方法中:

for(int i=0;i<3;++i)
{
    if (File.Exists(@"C:\MonitorFiles\BOT-PC-8is" + i.ToString() + ".txt"))
        labels[i].BackColor = Color.Green;
}

答案 2 :(得分:1)

这个怎么样:

Dictionary<string, KeyValuePair<Control, Color>> filesAndColors = new Dictionary<string, KeyValuePair<Control, Color>>();
foreach(KeyValuePair<string, KeyValuePair<Control, Color>> kvp in filesAndColors) 
{
    if(File.Exists(kvp.Key))
        kvp.Value.Key.BackColor = kvp.Value.Value;
}

这里的第一个键是要查找的文件的名称,然后第二个键(Value.Key)将是您想要更改颜色的控件,最终值将是您的颜色。