在项目中经常遇到要动态生成控件,动态显示指定的控件或者隐藏,这就要涉及到查找控件的问题。

       下面介绍下Winform中使用控件名来查找窗体或者容器中的控件的方法,代码如下:

        /// <summary>
            /// 通过控件名获取控件
            /// </summary>
            /// <param name="strName"></param>
            /// <returns></returns>
            private Control GetPbControl(string strName)
            {
                string pbName = strName;
                return GetControl(this, pbName);
            }
            /// <summary>
            /// 通过控件名获取控件
            /// </summary>
            /// <param name="ct">控件所在的容器或者窗体</param>
            /// <param name="name">需要查找的控件名</param>
            /// <returns></returns>
            public static Control GetControl(Control ct, string name)
            {
                Control[] ctls = ct.Controls.Find(name, false);
                if (ctls.Length > 0)
                {
                    return ctls[0];
                }
                else
                {
                    return null;
                }
            }

           查找控件的 Demo代码如下:

            strPxName = "SoftKeyBoard";
                Control sk = GetPbControl(strPxName);
                if (sk == null)
                {
                    return;
                }

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐