问个小问题..请大家多多指教...关于foreach()的
foreach (Control ctrl in panel1.Controls)
{
if (ctrl is Label)
MessageBox.Show(((Label)ctrl).Text);
}
我刚才想了一下还是没有解决的方法,不知道如何下手.以前也没有用过这个foreach问题是这个样子的:在panel里边有几个label.我想取出第一个,和另一个panel里边的label第一个数据进行比较.依次类推..第二 个...因为在panel1和panel2里边有很多个label,不知道如何才能取出某一个label里边的值...(现在是都能够读出来,就差取某一个值了....)
------解决方案-------------------- private void ComepareLabel(Panel panel1, Panel panel2)
{
int count1 = GetLabelCount(panel1);
int count2 = GetLabelCount(panel2);
for (int i = 0; i < count1; ++i)
{
for (int j = 0; j < count2; ++j)
{
Label lable1 = GetLabel(panel1, i);
Label lable2 = GetLabel(panel2, i);
if (lable1.Text == lable2.Text)
{
}
}
}
}
private int GetLabelCount(Panel panel)
{
int cout = 0;
foreach (Control ctrl in panel.Controls)
{
if (ctrl is Label)
{
++cout;
}
}
}
private Label GetLabel(Panel panel,int labelIndex)
{
int index = 0;
foreach (Control ctrl in panel.Controls)
{
if (ctrl is Label)
{
if (labelIndex == index)
{
return (Label)ctrl;
}
}
}
}
------解决方案--------------------感觉好像是这个意思,不知道对不对
ArrayList panel1Text = new ArrayList();
ArrayList panel2Text = new ArrayList();
ArrayList panel3Text = new ArrayList();
foreach (Control ctrl1 in panel1.Controls)
{
if (ctrl1 is Label)
{
panel1Text.Add(Convert.ToInt32( ctrl1.Text));
}
}
foreach (Control ctrl2 in panel2.Controls)
{
if (ctrl2 is Label)
{
panel2Text.Add(Convert.ToInt32(ctrl2.Text));
}
}
foreach (Control ctrl3 in panel3.Controls)
{
if (ctrl3 is TextBox)
{
panel3Text.Add(Convert.ToInt32(ctrl3.Text));
}
}
for (int i = 0; i < panel1Text.Count; i++)
{
for (int j = 0; j < panel2Text.Count; j++)
{
for (int z = 0; z < panel3Text.Count; z++)
{
int a = (int)panel1Text[i];
int b = (int)panel2Text[j];
int k = a+b;
if (k == (int)panel3Text[z])
{
MessageBox.Show(panel1Text[i]+" + "+panel2Text[j]+"="+panel3Text[z]);
}
}
}
}