我正在尝试创建一个循环,循环遍历组框中的所有控件,并找到其中包含文本的每个控件,并将tabstop属性设置为false。但是一些控件的tabstop属性必须始终为true,即使控件中有文本。
这是我的代码:
foreach (Control c in deliveryGroup.Controls)
{
if (c is Label || c is Button)
{
c.TabStop = false;
}
else
{
if (!string.IsNullOrEmpty(c.Text))
{
c.TabStop = false;
}
else if (c.Name == "cmbPKPAdrID")
{
}
else if (c.Name.ToString() == "cmbPKPType")
{
c.TabStop = true; <<------- never enters here
}
else if (c.Name.ToString() == "dtpPKPDate")
{
c.TabStop = true; <<------- never enters here
}
else
{
c.TabStop = true;
}
}
}
我的问题是我的程序运行,但从未遇到我用箭头标记的代码。它会跳出并将tabstop属性设置为false,即使我希望它在控件具有特定名称时将其设置为true。
我做错了什么?
答案 0 :(得分:2)
我在猜测代码行
if (!string.IsNullOrEmpty(c.Text))
正在为您不想将TabStop
设置为false的控件执行,并且该控件当前包含一些文本。
要解决此问题,请按以下方式重新排序测试:
foreach (Control c in deliveryGroup.Controls)
{
if (c is Label || c is Button)
{
c.TabStop = false;
}
else
{
if (c.Name == "cmbPKPAdrID")
{
}
else if (c.Name == "cmbPKPType")
{
c.TabStop = true;
}
else if (c.Name == "dtpPKPDate")
{
c.TabStop = true;
}
else if (!string.IsNullOrEmpty(c.Text))
{
c.TabStop = false;
}
else
{
c.TabStop = true;
}
}
}
您可以简化为此:
foreach (Control c in deliveryGroup.Controls)
{
if (c is Label || c is Button)
{
c.TabStop = false;
}
else
{
if (c.Name == "cmbPKPAdrID")
{
}
else if (c.Name == "cmbPKPType")
{
c.TabStop = true;
}
else if (c.Name == "dtpPKPDate")
{
c.TabStop = true;
}
else
{
c.TabStop = string.IsNullOrEmpty(c.Text);
}
}
}