按名称查找文本框、复选框、任何对象 C# [英] Find textBox, checkBox, any object by name C#

查看:44
本文介绍了按名称查找文本框、复选框、任何对象 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

在本例中,它获取复选框的名称(即 checkBox1、checkBox2 等).

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

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

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.

感谢阅读!

推荐答案

以下将循环使用 10 个用作评级星的图片框,在我的情况下将它们从灰色变为蓝色.图片框的命名遵循以下约定,pbStarX.其中 X 是 1-10 的数字.例如:pbStar1、pbStar2、pbStar3 等...

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...

注意:使用 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 时的替代方法

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();
}

这篇关于按名称查找文本框、复选框、任何对象 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆