利用反射动态创建控件,且修改其属性

来源:互联网 发布:python 多线程实例 编辑:程序博客网 时间:2024/05/20 08:27

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
//using System.Data;
namespace WindowsFormsApplication2
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }

        
private void Form1_Load(object sender, EventArgs e)
        {

        }
        //DataTable dt 
= new DataTable();
        Assembly asm;
        
private void Form1_Activated(object sender, EventArgs e)
        {
            fillDgv(toolStripTextBox1.Text);
        }

        
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            
try
            {
                splitContainer3.Panel2.Controls.Clear();
                System.Type t 
= asm.GetType((string)dataGridView1.CurrentRow.Cells[0].Value);
                
object obj = Activator.CreateInstance(t);
                propertyGrid1.SelectedObject 
= obj;
                Control c 
= obj as Control;
                splitContainer3.Panel2.Controls.Add(c);
            }
            
catch
            {
            }
        }

        
private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            
if (e.KeyChar == (char)Keys.Enter)
                fillDgv(toolStripTextBox1.Text);
        }

        
private void fillDgv(string assemblyPath)
        {
            dataGridView1.Rows.Clear();
            asm 
= Assembly.LoadFrom(assemblyPath);
            System.Type[] ts 
= asm.GetTypes();
            
foreach (System.Type t in ts)
            {
                dataGridView1.Rows.Add(t.FullName);
            }
        }
        
    }
}

原创粉丝点击