当前位置: 移动技术网 > IT编程>开发语言>c# > WinForm遍历窗体所有子控件的方法

WinForm遍历窗体所有子控件的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了winform遍历窗体所有子控件的方法。分享给大家供大家参考,具体如下:

/// <summary>
/// c# 只遍历控件子控件,不遍历孙控件
///当控件有子控件时,需要用递归的方法遍历,才能全部列出控件上的控件
/// </summary>
/// <typeparam name="t">控件类型</typeparam>
/// <param name="control">要遍历的控件</param>
/// <param name="controlsname">控件名</param>
/// <returns></returns>
public static t getcontrol<t>(control control, string controlsname) where t : control
{
  if (control == null) return null;
  control _control;
  for (int i = 0; i < control.controls.count; i++)
  {
    _control = control.controls[i];
    if (_control == null) return null;
    if (_control.name == controlsname && _control is t)
      return (t)_control;
    if (_control.haschildren)
    {
      _control = getcontrol<t>(_control, controlsname);
      if (_control != null)
        return (t)_control;
    }
  }
  return null;
}
/// <summary>
/// 遍历窗体所有子控件
/// </summary>
/// <typeparam name="t">控件类型</typeparam>
/// <param name="form">窗体名</param>
/// <param name="controlsname">控件名</param>
/// <returns></returns>
public static t getcontrol<t>(form form, string controlsname) where t : control
{
  t _control = null;
  for (int i = 0; i < form.controls.count; i++)
  {
    _control = getcontrol<t>(form.controls[i], controlsname);
    if (_control != null)
      return _control;
  }
  return null;
}

更多关于c#相关内容感兴趣的读者可查看本站专题:《winform控件用法总结》、《c#窗体操作技巧汇总》、《c#常见控件用法教程》、《c#程序设计之线程使用技巧总结》、《c#操作excel技巧总结》、《c#中xml文件操作技巧汇总》、《c#数据结构与算法教程》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程

希望本文所述对大家c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网