不进则退

Roger's blog @cnblogs

导航

Winform下通过控件名称来获取控件

以前一直在Webform下用Control.FindControl(string)方法来获取页面上的某个控件,可是Winform下面的ControlCollection却没有提供FindControl的方法:
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemwindowsformscontrolcontrolcollectionmemberstopic.asp?frame=true

没办法,只好自己建一个Hash表来实现。


        //Populate data

        
ushort[] mydata = new ushort[]{111,222,333,444,555,666,777,888,999,1000};

                        

                        
//Create a Hashtable reference to all the TextBoxes

                        Hashtable htTextBox 
= new Hashtable();

                        
foreach (Control c in this.Controls)

                        
{

                                
if (c.GetType().ToString() == "System.Windows.Forms.TextBox")

                                        htTextBox.Add(c.Name,c);

                        }


                        
//Search TextBox from Hashtable and evalute it.

                        
for (int i=0;i<10;i++)

                        
{

                                TextBox t;

                                t 
= (TextBox)htTextBox["textBox"+(i+1).ToString()];

                                t.Text 
= mydata[i].ToString();

                        }
 

查了下.NET Framework 2.0的文档,果然发现.NET 2.0中给Control.ControlCollection对象增加了名为Find的方法...
http://msdn2.microsoft.com/library/1hb809fy.aspx


本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利

posted on 2005-02-07 16:53  Roger Wo  阅读(3044)  评论(1编辑  收藏  举报