查找文本框、复选框、按名称 C# 列出的任何对象

本文关键字:任何 对象 文本 复选框 查找 | 更新日期: 2023-09-27 18:36:45

这真的很奇怪,但我似乎在.NET CF中找不到特定的textBox(i)或checkBox(i)。 在.NET 3.5中,我可以创建这个函数:

void checking(int input)
{
    CheckBox checkbox = (CheckBox)this.Controls["checkBox" + input.toString()];
    if(checkbox.isChecked)
      //do something here
}

在此示例中,它获取复选框的名称(即复选框 1、复选框 2 等)。

但是,在 WINCE6 的 .NET CF 3.5 中,它不断告诉我我需要在 Controls[] 中有一个索引,因为它无法将字符串转换为 int。有谁知道如何在不使用 foreach 语句的情况下找到特定对象?foreach 很有用,但不是这个,因为它循环遍历所有复选框。由于我使用的是基于 ARM 的开发,因此速度就是一切。我正在使用VS2008 C#开发桌面和移动应用程序。

感谢您的阅读!

查找文本框、复选框、按名称 C# 列出的任何对象

以下内容将循环浏览 10 个用作评级星星的图片框,在我的情况下将它们从灰色更改为蓝色。 PictureBoxs按照以下约定pbStarX命名。 其中 X 是数字 1-10。 例如:pbStar1,pbStar2,pbStar3等...

注意:使用 c#.Net VS 2010

for (int x = 1; x <= 10; x++)
{
    PictureBox pb = (PictureBox)this.Controls.Find("pbStar" + x, true)[0];
    pb.Image = MyProject.Properties.Resources.star_blue;
}

使用c#.Net Compact Framework时的替代方案

private Control FindControl(Control parent, string ctlName)
{
    foreach(Control ctl in parent.Controls)
    {
        if(ctl.Name.Equals(ctlName))
        {
            return ctl;
        }
        FindControl(ctl, ctlName);                     
    }
    return null;
}

像这样使用上面的函数...

Control ctl = FindControl(this, "btn3");
if (ctl != null)
{
    ctl.Focus();
}

您正在使用 un 整数索引器,应将 un integer 传递给它以检索对象。尝试这样的事情:

void checking(int input) 
{ 
    CheckBox checkbox = (CheckBox)this.FindControl("checkBox" + input.toString()); 
    if(checkbox.isChecked) 
      //do something here 
} 

这样,您将通过id找到控件

它应该可以工作,但您也可以使用

CheckBox checkbox = (CheckBox)this.Controls.Find("checkBox" + input.toString())[0];

它正在工作我的朋友:)请尝试这种方式

bool chkValue;
string chkName="checkbox1";
CheckBox myCheckBox = this.Controls.Find(chkName, true).First() as CheckBox;
chkValue = myCheckBox.Checked;