• 怎样在不对控件类型进行硬编码的情况下在 C#vs 中动态添加控件


    文章ID: 815780

    最近更新: 2004-1-12


    这篇文章中的信息适用于:
    • Microsoft Visual C# .NET 2003 标准版
    • Microsoft Visual C# .NET 2002 标准版

    有关本文的 Microsoft Visual Basic .NET 版本,请参阅 311321。
    本文引用下面的 Microsoft .NET Framework 类库名称空间:
    • System.Reflection
     

    本任务的内容

    概要

    本文分步介绍了如何在 Visual C# .NET 中向窗体动态添加控件和如何响应控件的事件。
    返回页首

    分步示例

    此部分介绍如何创建一个项目来演示如何在 Visual C# .NET 中向窗体动态添加控件和如何响应控件的事件。
    1. 启动 Microsoft Visual Studio .NET。
    2. 在“文件”菜单上,指向“新建”,然后单击“项目”。
    3. 单击“项目类型”下的“Visual C# 项目”,然后单击“模板”下的“Windows 应用程序”。默认情况下,Form1 将添加到该项目中。
    4. 将下面的代码添加到“Form1 代码”窗口的顶部:
      using System.Reflection;
    5. 从工具箱拖出两个“Button”控件和一个“ComboBox”控件,然后将这些控件放在 Form1 底部附近。您将动态地将这些控件添加到窗体顶部。
    6. 在“属性”窗口中,按照下面的方法更改这些控件的“名称”和“文本”属性:
      控件名称文本属性
      button1 btnAddControl 添加控件
      button2 btnRemoveControl 删除控件
      comboBox1 cboControlType 选择控件类型
    7. 粘贴下面的代码作为 Form1 定义的前几个语句:
      TreeView DynTreeview;
      TextBox DynTextBox;
      ListBox DynListBox;
      Control ControlObject;
    8. 切换到“设计”视图,然后双击“Form1”以将插入点定位到“Form1_Load”事件的第一行。
    9. 将下面的代码添加到“Form1_Load”事件中:
      this.btnAddControl.Click += new System.EventHandler(this.btnAddControl_Click);
      this.btnRemoveControl.Click += new System.EventHandler(this.btnRemoveControl_Click);
      cboControlType.Items.AddRange(new object[3]{"TreeView","ListBox","TextBox"});
    10. 将下面的代码粘贴到 Form1 的“Windows 窗体设计器生成的代码”区域:
      private void AddControl(string ControlName, string ControlType)
      {
         System.Reflection.Assembly asm;
         asm = typeof(Form).Assembly;
         ControlObject = (System.Windows.Forms.Control)asm.CreateInstance(ControlType);
         ControlObject.Name = ControlName;
         ControlObject.Location = new System.Drawing.Point(20, 20);
         this.Controls.Add(ControlObject);
      
         if (ControlType.EndsWith("TreeView"))
         {
            DynTreeview = (System.Windows.Forms.TreeView)ControlObject;
            DynTreeview.Width = 200;
            DynTreeview.Height = 120;
            DynTreeview.Nodes.Add(new TreeNode("Root"));
            DynTreeview.Nodes.Add("FirstChild");
            DynTreeview.Nodes.Add("SecondChild");
            DynTreeview.ExpandAll();
            DynTreeview.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(DynTree_AfterSelect);
         }
         else if (ControlType.EndsWith("ListBox"))
         {
            DynListBox = (System.Windows.Forms.ListBox)ControlObject;
            DynListBox.Width = 200;
            DynListBox.Height = 120;
            DynListBox.Items.AddRange(new object[3]{"Apples", "Banana", "Oranges"});
            DynListBox.SelectedIndexChanged += new System.EventHandler(DynCtrl_Event);
         }
         else if (ControlType.EndsWith("TextBox"))
         {
            DynTextBox = (System.Windows.Forms.TextBox)ControlObject;
            DynTextBox.Width = 200;
            DynTextBox.Text = "Dynamically Added Textbox.";
            DynTextBox.DoubleClick += new System.EventHandler(DynCtrl_Event);
         }
      }
      
      private void btnAddControl_Click(object sender, System.EventArgs e)
      {
         string CtrlType;
      
         if (!(ControlObject == null))
         {
            btnRemoveControl.PerformClick();
         }
      
         if (cboControlType.SelectedIndex < 0)
         {
            MessageBox.Show("Select a Control Type to add.");
            return;
         }
      
         CtrlType = "System.Windows.Forms." + cboControlType.SelectedItem.ToString();
         this.AddControl("myControl", CtrlType);
      }
      
      private void DynCtrl_Event(object sender, System.EventArgs e)
      {
         if (sender.GetType().ToString().EndsWith("ListBox"))
         {
            MessageBox.Show("The item you selected is: " + DynListBox.SelectedItem.ToString());
         }
         else if (sender.GetType().ToString().EndsWith("TextBox"))
         {
            Clipboard.SetDataObject(DynTextBox.Text);
            MessageBox.Show("The Text is copied to the clipboard.");
         }
      }
      
      private void btnRemoveControl_Click(object sender, System.EventArgs e)
      {
         this.Controls.Remove(ControlObject);
         ControlObject = null;
      }
      
      private void DynTree_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
      {
         MessageBox.Show("The Node you clicked on is: " + e.Node.Text);
      }
    11. 保存项目。
    12. 若要运行项目,请单击“调试”菜单中的“开始”。
    13. 在组合框中,单击“TreeView”作为控件类型,然后单击“添加控件”。您会注意到添加了一个新的 TreeView 控件。单击任何节点,测试 TreeView 的“AfterClick”事件。
    返回页首

    代码讨论

    • 在此示例中,ComboBox 控件包含一个要动态添加的控件类型的列表。您需要将此列表填充到窗体的 Load 事件中。
    • 因为您在 Form1 定义的前面几个语句中声明了三个特定的控件对象,因此您可以在程序中分别使用这些控件对象的功能。通过声明特定的控件类型,您还可以在编程时访问 Microsoft IntelliSense。
    • btnAddControl_Click 事件处理程序中,检查以确定是否已加载了另一个控件。如果是,请删除现有的控件,然后添加在组合框中选定的新控件。还需要确保在组合框中作的选择有效。如果选择无效,程序将生成一个信息框,并退出事件处理程序而不继续处理语句。如果选择有效,则可以使用适当的参数调用 AddControl 方法。
    • AddControl 方法中,您已将 asm 声明为 System.Reflection.Assembly 类型。typeof(Form) 语句返回 Form 类型的类型对象。然后使用此对象的 Assembly 方法检索定义了 Form 类的程序集的实例。在程序集之后,将创建 asm 对象。您使用 asm 对象的 CreateInstance 方法和一个 ControlType 字符串参数创建了该控件的一个实例。在创建此控件后,您使用 this.Controls.Add 方法将其添加到当前的窗体。然后,通过使用 String 类的 EndsWith 方法,您检查作为第二个参数传递到此过程的控件的类型。根据控件类型,您在 if...else...if... 代码块中设置了控件的个别属性。您使用 += 操作符将动态添加的控件的特定事件连接到事件处理程序。对于 ListBoxTextBox 控件,您将 SelectedIndexChangedDoubleClick 事件连接到 DynCtrl_Event 事件处理程序。对于 TreeView 控件,您使用了一个单独的事件处理程序 (DynTree_AfterSelect) 将此控件连接到 TreeView 控件的 AfterSelect 事件。
    • TreeView 控件的事件处理程序要求一个与其他两个控件不同的签名。“DynTree_AfterSelect”事件处理程序的第二个参数的类型是“System.Windows.Forms.TreeViewEventArgs”;对于“DynCtrl_Event”事件处理程序,您使用了类型“System.EventArgs”。“System.Windows.Forms.TreeViewEventArgs”类型提供了附加的信息,如选定节点的属性。
    返回页首

    参考

    有关在控件类型是硬编码时在窗体上添加控件的更多信息,请访问下面的 Microsoft Developer Network (MSDN) Web 站点: 有关事件处理程序的详细信息,请访问下面的 MSDN Web 站点: 返回页首

    Keywords: kbhowtomaster kbwindowsforms kbide kbnamespace kbtreeview kblistbox kbprogramming kbctrlcreate kbforms kbbutton kbcombobox kbevent KB815780

    转载请注明文章来自:程序猴(http://www.chengxuhou.com/)
  • 相关阅读:
    转载:c++内存泄露机制
    推荐一款不错的dialog小工具:artDialog
    写的一些推广方法 拿出来分享下
    struts2标签具体解释
    父亲节:再见,总有一天
    Hadoop是什么
    熊猫烟花集团完美见证异速联远程接入系统
    OpenStack Networking
    管道(Pipe)/createPipe
    百度2014校园招聘算法——给出一组数据A=[a_0, a_1, a-2, ... a_n](当中n可变),打印出该数值元素的全部组合。
  • 原文地址:https://www.cnblogs.com/minotmin/p/3320682.html
Copyright © 2020-2023  润新知