zoukankan      html  css  js  c++  java
  • [转] WinForm自定义函数FindControl实现按名称查找控件

    原文地址 WinForm自定义函数FindControl实现按名称查找控件

    本文所述实例实现WinForm自定义函数FindControl实现按名称查找控件的功能,在C#程序开发中有一定的实用价值。

    /// <summary>
    /// 按名称查找控件
    /// </summary>
    /// <param name="parentControl">查找控件的父容器控件</param>
    /// <param name="findCtrlName">查找控件名称</param>
    /// <returns>若没有查找到返回NULL</returns>
    public static Control FindControl(this Control parentControl, string findCtrlName)
    {
      Control _findedControl = null;
      if (!string.IsNullOrEmpty(findCtrlName) && parentControl != null)
      {
     foreach (Control ctrl in parentControl.Controls)
     {
       if (ctrl.Name.Equals(findCtrlName))
       {
     _findedControl = ctrl;
     break;
       }
     }
      }
      return _findedControl;
    }
    /// <summary>
    /// 将Control转换某种控件类型
    /// </summary>
    /// <typeparam name="T">控件类型</typeparam>
    /// <param name="control">Control</param>
    /// <param name="result">转换结果</param>
    /// <returns>若成功则返回控件;若失败则返回NULL</returns>
    public static T Cast<T>(this Control control, out bool result) where T : Control
    {
      result = false;
      T _castCtrl = null;
      if (control != null)
      {
        if (control is T)
        {
          try
          {
            _castCtrl = control as T;
            result = true;
          }
          catch (Exception ex)
          {
            Debug.WriteLine(string.Format("将Control转换某种控件类型异常,原因:{0}", ex.Message));
            result = false;
          }
        }
      }
      return _castCtrl;
    }
    

     测试代码

    bool _sucess = false;
    CheckBox _finded = panel1.FindControl("checkBox1").Cast<CheckBox>(out _sucess);
    if (_sucess)
    {
        MessageBox.Show(_finded.Name);
    }
    else
    {
        MessageBox.Show("Not Finded.");
    }
    
  • 相关阅读:
    IntelliJ IDEA设置JVM运行参数
    IntelliJ IDEA 乱码解决方案 (项目代码、控制台等)
    188.索引与视图
    187.数据库操作
    186.元素
    185.流程设计
    184.数据操纵语言DML
    改变linux shell前景色和背景色
    Centos文本方式安装情况下lvm分区的创建
    深入理解计算机系统第二版习题解答CSAPP 2.20
  • 原文地址:https://www.cnblogs.com/arxive/p/5885026.html
Copyright © 2011-2022 走看看