zoukankan      html  css  js  c++  java
  • 通过反射给窗体赋值

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Reflection;

    namespace puhlish
    {
       
    /// <summary> 
       
    /// 测试窗体 
       
    /// </summary> 
       public partial class frmTest : Form
       {
          
    public frmTest()
          {
             InitializeComponent();
          }    
          
    private void button1_Click(object sender, EventArgs e)
          {
             
    //不直接创建 
             
    // frmReflactForm form = new frmReflactForm(); 
             
    //为了演示,通过反射创建一个窗体 
             object o = typeof(frmReflactForm).Assembly.CreateInstance("puhlish.frmReflactForm");
             frmReflactForm form 
    = o as frmReflactForm;
             form.Show();
          }
          
    private void button2_Click(object sender, EventArgs e)
          {
             
    //在Assembly内通过Application查找frmReflactForm 
             Form findform = GetReflactForm("frmReflactForm");
             
    if (findform != null)
                 SetFormValue(findform, 
    "textBox2", textBox1.Text);
          }
          
    private void SetFormValue(Form form, string controlName, object value)
          {
             FieldInfo[] fs 
    = form.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
             
    foreach (FieldInfo fi in fs)
             {
                
    if (fi.Name.ToUpper() == controlName.ToUpper())
                {
                   Control[] ctls 
    = form.Controls.Find(controlName, true);
                   
    if (ctls.Length > 0)
                   {
                      ctls[
    0].Text = Convert.ToString(value); //直接赋值 
                      
    //如想搞得高级点,通过反射赋值.xxx.setvalue(obj,value) 
                   }
                   
    break;
                }
             }
          }
          
    //从Application查找窗体 
          private Form GetReflactForm(string formName)
          {
             
    foreach (Form form in Application.OpenForms)
             {
                
    if (form.GetType().Name.ToUpper() == formName.ToUpper())
                {
                   
    return form;
                }
             }
             
    return null;
          }
       }
  • 相关阅读:
    css点滴3—5种方式实现圆环
    css点滴2—六种方式实现元素水平居中
    css点滴1—八种方式实现元素垂直居中
    当我们在讨论CQRS时,我们在讨论些神马?
    CSDN屏蔽广告
    手撸一套纯粹的CQRS实现
    【转】CAP 定理的含义
    【转】浅谈命令查询职责分离(CQRS)模式
    Castle DynamicProxy基本用法(AOP)
    【转】面向对象设计的SOLID原则
  • 原文地址:https://www.cnblogs.com/kakaliush/p/1727735.html
Copyright © 2011-2022 走看看