且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[转] WinForm自定义函数FindControl实现按名称查找控件

更新时间:2022-09-14 18:10:45

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/// <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;
}

 测试代码

1
2
3
4
5
6
7
8
9
10
bool _sucess = false;
CheckBox _finded = panel1.FindControl("checkBox1").Cast<CheckBox>(out _sucess);
if (_sucess)
{
    MessageBox.Show(_finded.Name);
}
else
{
    MessageBox.Show("Not Finded.");
}

 

没有整理与归纳的知识,一文不值!高度概括与梳理的知识,才是自己真正的知识与技能。 永远不要让自己的***、好奇、充满创造力的想法被现实的框架所束缚,让创造力***成长吧! 多花时间,关心他(她)人,正如别人所关心你的。理想的腾飞与实现,没有别人的支持与帮助,是万万不能的。




    本文转自wenglabs博客园博客,原文链接:http://www.cnblogs.com/arxive/p/5885026.html,如需转载请自行联系原作者