Find textBox, checkBox, any object by name C#

扶醉桌前 提交于 2019-12-12 01:07:32

问题


This is really weird, but I can't seem to find a specific textBox(i) or checkBox(i) in .NET CF. In .NET 3.5 I can create this function:

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

In this example, it gets the name of the checkBox (i.e checkBox1, checkBox2, etc).

However in .NET CF 3.5 for WINCE6, it keeps on telling me that I need an index inside Controls[] because it can't convert string to int. Does anyone know how to find the specific object without using that foreach statement? That foreach is useful but not for this because it loops through all the checkBoxes. Since I'm developing in ARM based, speed is everything. I'm using VS2008 C# to develop a desktop and mobile app.

Thanks for reading!


回答1:


The following will cycle through 10 PictureBoxs used as rating stars changing them from gray to blue in my case. The PictureBoxs are named in the following convention, pbStarX. Where X is a number 1-10. Ex: pbStar1, pbStar2, pbStar3, etc...

Note: Using 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;
}

Alternative maybe when using 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;
}

Use the above function like this...

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



回答2:


Its should work, but alternatively you can use

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


来源:https://stackoverflow.com/questions/10985584/find-textbox-checkbox-any-object-by-name-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!