C# 中通过控件名 进行控件操作的示例

  C#中对于控件的使用是经常的,如何对控件进行控制交替的性的控制也是经常会遇到的问题。

  笔者编程中发现,将控件的名字放到字符串中,然后通过Controls.Find()方法去找到并强制转换,是很方便的。

  例程如下:

  定义字符串数组,用以存放控件名:

        string[] strDC_double = { "DC_A_13", "DC_A_13", "DC_A_13", "DC_A_13", "DC_A_24", "DC_A_24", "DC_A_24", "DC_A_24",
                                  "DC_B_13","DC_B_13","DC_B_13","DC_B_13", "DC_B_24", "DC_B_24", "DC_B_24", "DC_B_24" };

 

        在方法中操作如下:

                    Control[] st=this.Controls.Find(strDC_double[j], true);//将强制转换后的控件放到数组中
                    Daocha_2 ctrl = (Daocha_2)st[0];//获得控件数组中的第一个,即刚刚转换的那个控件
                    if (strProtocol[i] == '0' && i % 4 == 0)
                    {
                        ctrl.定反位上 = Daocha_2.DingFan.定位;    //双动道岔上,定位
                    }
                    else if (strProtocol[i] == '1' && i % 4 == 0)
                    {
                        ctrl.定反位上 = Daocha_2.DingFan.反位;     //双动道岔上,反位
                    }
                    else if (strProtocol[i] == '0' && i % 4 == 1)
                    {
                        ctrl.锁闭状态上 = Daocha_2.STATE.空闲;   //双动道岔上,空闲
                    }
                    else if (strProtocol[i] == '1' && i % 4 == 1)
                    {
                        ctrl.锁闭状态上 = Daocha_2.STATE.锁闭;   //双动道岔上,锁闭
                    }
                    else if (strProtocol[i] == '2' && i % 4 == 1)
                    {
                        ctrl.锁闭状态上 = Daocha_2.STATE.占用;   //双动道岔上,占用
                    }
                    else if (strProtocol[i] == '0' && i % 4 == 2)
                    {
                        ctrl.定反位下 = Daocha_2.DingFan.定位;     //双动道岔下,定位
                    }
                    else if (strProtocol[i] == '1' && i % 4 == 2)
                    {
                        ctrl.定反位下 = Daocha_2.DingFan.反位;     //双动道岔下,反位
                    }
                    else if (strProtocol[i] == '0' && i % 4 == 3)
                    {
                        ctrl.锁闭状态下 = Daocha_2.STATE.空闲;   //双动道岔下,空闲
                    }
                    else if (strProtocol[i] == '1' && i % 4 == 3)
                    {
                        ctrl.锁闭状态下 = Daocha_2.STATE.锁闭;   //双动道岔下,锁闭
                    }
                    else if (strProtocol[i] == '2' && i % 4 == 3)
                    {
                        ctrl.锁闭状态下 = Daocha_2.STATE.占用;   //双动道岔下,占用
                    }

posted @ 2013-05-16 16:25  在路上的人  阅读(1303)  评论(0)    收藏  举报