C# Winform动态设置控件的值及反射技术应用
作者:C/S原创  发布日期:2011/03/26 11:19:42
C# Winform动态设置控件的值及反射技术

批量给控件赋值
假设我们已知控件名的情况下,此方式适合查找命名不规范的控件.
假设我们已知控件名的情况下,但是控件所在的窗体或容器也是动态创建的.
获取窗体内所有字段定义.

贴图图片


批量给控件赋值

private void button1_Click(object sender, EventArgs e)
{
   //
   //批量给控件赋值
   //
   //通过控件的名字查找控件对象, 当找到该控件就赋值.
   //这种方法要求控件的命名要有规律.
   //
   for (int i = 1; i <= 5; i )
   {
      //
      //调用Controls.Find方法查找控件.
      //
      //Find()方法说明:
      // Searches for controls by their System.Windows.Forms.Control.Name property
      // and builds an array of all the controls that match.
      //参数:
      // key: <控件名称>
      // The key to locate in the System.Windows.Forms.Control.ControlCollection.
      //
      // searchAllChildren:<查找所有子控件,递归查找>
      // true to search all child controls; otherwise, false.
      Control[] ctrs = this.Controls.Find("txtPhotoName" i.ToString(), true);
      
      //查找到,赋值
      if (ctrs.Length > 0) (ctrs[0] as TextBox).Text = "Name:" ctrs[0].Name;
   }
}


// 来源:www.CSFramework.com, C/S结构框架学习网


假设我们已知控件名的情况下,此方式适合查找命名不规范的控件.

private void button2_Click(object sender, EventArgs e)
{
   //
   //假设我们已知控件名的情况下,此方式适合查找命名不规范的控件.
   //
   //要查找的控件名. 名称可自定义
   string names = "txtPhotoName1,txtPhotoName2,txtPhotoName3,txtPhotoName4,txtPhotoName5";
   
   //使用分隔符(Char类型)转换成数组
   string[] nameArray = names.Split(new Char[] { Char.Parse(",") });
   
   foreach (string name in nameArray)
   {
      if (String.IsNullOrEmpty(name)) continue; //名字为空,不处理, 注意:String.IsNullOrEmpty方法
      
      Control[] ctrs = this.Controls.Find(name, true); //在当前窗体内查找
      if (ctrs.Length > 0) (ctrs[0] as TextBox).Text = "方法2:" ctrs[0].Name;
   }
}


// 来源:www.CSFramework.com, C/S结构框架学习网


假设我们已知控件名的情况下,但是控件所在的窗体或容器也是动态创建的.

private void button3_Click(object sender, EventArgs e)
{
   //
   //假设我们已知控件名的情况下,但是控件所在的窗体或容器也是动态创建的.
   //
   
   //使用反射技术给对象的属性或控件赋值
   PropertyInfo pi = this.GetType().GetProperty("TestName");
   if (pi != null) pi.SetValue(this, "使用反射技术给对象的属性或控件赋值", null);
   
   //跟据名字获取字段对象
   FieldInfo fi = this.GetType().GetField("txtPhotoName1", BindingFlags.Instance | BindingFlags.NonPublic);
   if (fi != null)
   {
      object o = fi.GetValue(this);
      (o as TextBox).Text = "方法3: I found you!";
   }
}


// 来源:www.CSFramework.com, C/S结构框架学习网


获取窗体内所有字段定义.

private void button4_Click(object sender, EventArgs e)
{
   //获取窗体内所有字段定义.
   //打开xxx.Designer.cs文件看到的 private System.Windows.Forms.ListBox listBox1;等等...
   FieldInfo[] fs = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
   
   foreach (FieldInfo fi in fs)
   {
      object o = fi.GetValue(this); //获取字段对象
      if (o != null)
      {
         if (o is Control) //判断类型
         {
            (o as Control).Text ="方法4:" (o as Control).Name;
            
            this.listBox1.Items.Add((o as Control).Name);
         }
      }
   }
}

// 来源:www.CSFramework.com, C/S结构框架学习网



点击下载附件 点击下载附件 (如下载失败,请邮件通知我们寄回给您,或QQ:23404761留言.)
上一篇 下一篇