C#中动态创建控件及事件处理程序

关键字:
  
  using System;
  using System.Drawing;
  using System.Collections;
  using System.ComponentModel;
  using System.Windows.Forms;
  using System.Data;
  
  namespace Miner
  {
    /// <summary>
      /// Summary des cription for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
        private System.Windows.Forms.Panel panel1;
        /// <summary>
        /// Required designer variable.
        /// </summary>
  
        private Button[] n =new Button[100];

        private int[] kn=new int[100];
  
        private System.ComponentModel.Container components = null;
  
        public Form1()
        {
          //
          // Required for Windows Form Designer support
          //

          InitializeComponent();
  
          //
          // TODO: Add any constructor code after InitializeComponent call
          //
        }
  
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
          if( disposing )
          {
            if (components != null)
            {
              components.Dispose();
            }
        }
          base.Dispose( disposing );
      }
  
      #region Windows Form Designer generated code
      /// <summary>
      /// Required method for Designer support - do not modify
      /// the contents of this method with the code editor.
      /// </summary>
      private void InitializeComponent()
      {
        this.panel1 = new System.Windows.Forms.Panel();
        this.SuspendLayout();
        //
        // panel1
        //
        this.panel1.Location = new System.Drawing.Point(8, 8);
        this.panel1.Name = "panel1";
        this.panel1.Size = new System.Drawing.Size(400, 400);
        this.panel1.TabIndex = 0;
        //
        // Form1
        //
        this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
        this.BackColor = System.Drawing.Color.White;
        this.ClientSize = new System.Drawing.Size(416, 413);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
        this.panel1});
        this.Name = "Form1";
        this.Text = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.ResumeLayout(false);  
      }
      #endregion
  
      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main()
      {
        Application.Run(new Form1());
      }
  
      private void Form1_Load(object sender, System.EventArgs e)
      {
        int a=0;
        int x=0,y=0;
        for (a=0;a<=99;a++)
        {
          n[a] = new Button();
          n[a].BackColor =Color.White;
          n[a].FlatStyle = FlatStyle.Flat;
          n[a].Width = panel1.Width / 10;
          n[a].Left = x * n[a].Width;
          n[a].Height = panel1.Height / 10;
          n[a].Top = y * n[a].Height;
          n[a].Name = "b" + a;
          panel1.Controls.Add(n[a]);
          panel1.Controls[a].MouseDown += new MouseEventHandler(this.ButtonArray_OnClick);
          
          x += 1;
          if (x == 10)
          {
           x = 0;
           y += 1;
          }
        }  
      }
  
      private void ButtonArray_OnClick(object sender, MouseEventArgs e)
      {
        MouseEventArgs arg=(MouseEventArgs)e;
        Button b1=(Button)sender;
        if (arg.Button==MouseButtons.Right )
            b1.BackColor=Color.White ;
        else
        {
          //b1.BackColor =Color.White ;
          b1.Image=Image.FromFile("f:\\my documents\\my pictures\\elements\\regular_smile.gif");
        }
      }
    }
  }
  
  
  
基于asp.net的web页面动态控件创建以及使用


摘要:

  web设计中,有很多场合,页面的控件要动态创建甚至只能动态创建,这样可以增加页面的灵活性,但是给程序员带来了一些麻烦,比如要使用动态创建的控件,怎么使用,都是要求解决的问题,本文基于asp.net,简要介绍了页面的控件如何动态创建,同时也介绍了怎么使用这些动态创建的控件的方法。

前言:

  自从Microsoft在2000年推出了.net framework以来,给基于internet编程的程序员带来了巨大的福音,.net framework大大简化了web页面设计的繁杂,可见即可得的页面效果大大简化了页面设计程序员的工作任务,code behind技术将页面与代码分离,减少了web页面的无序状态,其中大量可以复用的控件可以无缝的被浏览器使用,由于互联网上95%的浏览器均是Microsoft的Internet Explorer,程序员大可以放心的使用这些控件而不用担心浏览器的兼容性,本文从Microsoft的.net和com控件开始,给出具体例子说明如何在页面上动态创建控件,以及怎么来使用这些动态创建的控件。其中具体使用的语言是vb.net。

1. Microsoft 控件

  目前用于浏览器的动态数据浏览方式主要有以下两种,(1).使用java applet。(2).使用可以在浏览器中运用的控件。两种方法各有利弊,使用java applet,页面执行较慢,编程复杂,可复用性不大,这种方式现在使用较少;越来越多的程序员较倾向于使用控件。其中我们在web中大多数时候是使用到.net 的web control和html control以及一些数据操作控件。

  一般的,在web设计中,通常使用拖拽的方式,将空间放置到页面,然后设置属性就可以了,然后再后台程序中编程使用就可以了。这种方式操作起来很方便,可见即可得,同时引用这些放置好的控件也很方便,但是在有些情况下,我们却不得不要动态创建控件,比如对一一个数据库中的某一些字段,对于不同身份的用户,见到的字段数目是不一样的;还有就是对于不同身份的用户对于某一控件的使能状态是不一样的,我们不能再页面设计时采用一个标准,最好的方式就是动态创建控件,对于不同的情况,通过程序来控制,放置在页面上的控件的数目也通过程序来控制。然后通过程序来引用这些创建好的控件。

2. 创建控件

  对于程序员来说,用例子说话是最好的方式来提供解决方案,我将在页面上动态的放置一些标签(label)和文本框(textbox),这些文本框里头放置的是从dataset取到的数据,同时我把这些文本框放置到一个表格的相应单元格里,可以实现有序的放置,首先在页面添加一个table。然后根据需要创建不同的列数和行数,如下为动态创建这些文本框的代码:

 Dim i As Integer

  For i = 0 To IntRowCount - 1

   Dim r As TableRow = New TableRow()
   Dim c1 As TableCell = New TableCell()
   Dim myLabel1 As Label = New Label()
  '这里设置该label的ID,对于不同的label,必须设置成不同的ID,我这里设置成前缀lbl1加字段名的组合,例如lbl1xlmc等。

  myLabel1.ID = "Lbl1" & Trim(OleDsField.Tables("Field").Rows(i).Item("column_name")).ToString()

  '下面的条件语句是为了判断数据库中在字段的值是否为空,根据条件赋予label不同的文本。
   If OleDsField.Tables("Field").Rows(i).Item("column_title").GetType.ToString = "System.DBNull" Then
   myLabel1.Text = ""
  Else
   myLabel1.Text = Trim(OleDsField.Tables("Field").Rows(i).Item("column_title"))
  End If

  c1.Controls.Add(myLabel1)
  r.Cells.Add(c1)

  Dim c2 As TableCell = New TableCell()
  Dim mytextbox As TextBox = New TextBox()
  mytextbox.ID = "Txt" & Trim(OleDsField.Tables("Field").Rows(i).Item("column_name")).ToString()
  If OleDsResult.Tables("Result").Rows(0).Item(i).GetType.ToString = "System.DBNull" Then
   mytextbox.Text = ""
  Else
   mytextbox.Text = Trim(OleDsResult.Tables("Result").Rows(0).Item(i))
  End If

  If Trim(OleDsField.Tables("Field").Rows(i).Item("column_enable")) = "是" Then
   mytextbox.Enabled = True

  Else
   mytextbox.Enabled = False

  End If
  c2.Controls.Add(mytextbox)
  r.Cells.Add(c2)

  Table3.Rows.Add(r)
 Next

  这样就成功地添加了两列到表里,至于行数由变量IntRowCount决定,其中IntRowCount为取数据库时得到的记录的行数

3. 使用动态创建的控件

  使用这些控件时,首先必须要知道这些控件的ID,对于上文所说的这些控件,由于ID名称不定,使用时必须也要根据条件来使用。比如我要找到相应的文本框的ID,就用以下代码可以实现:

  Dim txt As TextBox
 txt = Me.FindControl("txt" & OleDsField.Tables("Field").Rows(i).Item("column_name"))

 这样就找到了要使用的文本框的这个控件,然后就可以使用相应功能。

4. 小结

  使用动态创建控件时,难点在于怎么来操作这些动态创建的控件。本文给出了代码,本文例子在.net 2002+windows 2000下调试通过。同时也给出了web设计的一个方法

C#中动态创建控件及事件处理程序

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

namespace Miner

{

 /// <summary>

 /// Summary des cription for Form1.

 /// </summary>

 public class Form1 : System.Windows.Forms.Form

 {

  private System.Windows.Forms.Panel panel1;

  /// <summary>

  /// Required designer variable.

  /// </summary>

  ///

  private Button[] n =new Button[100];

  private int[] kn=new int[100];

  private System.ComponentModel.Container components = null;

  public Form1()

  {

   //

   // Required for Windows Form Designer support

   //

   InitializeComponent();

   //

   // TODO: Add any constructor code after InitializeComponent call

   //

  }

  /// <summary>

  /// Clean up any resources being used.

  /// </summary>

  protected override void Dispose( bool disposing )

  {

   if( disposing )

   {

    if (components != null)

    {

     components.Dispose();

    }

   }

   base.Dispose( disposing );

  }

   #region Windows Form Designer generated code

   /// <summary>

   /// Required method for Designer support - do not modify

   /// the contents of this method with the code editor.

   /// </summary>

   private void InitializeComponent()

   {

    this.panel1 = new System.Windows.Forms.Panel();

    this.SuspendLayout();

    //

    // panel1

    //

    this.panel1.Location = new System.Drawing.Point(8, 8);

    this.panel1.Name = "panel1";

    this.panel1.Size = new System.Drawing.Size(400, 400);

    this.panel1.TabIndex = 0;

    //

    // Form1

    //

    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

    this.BackColor = System.Drawing.Color.White;

    this.ClientSize = new System.Drawing.Size(416, 413);

    this.Controls.AddRange(new System.Windows.Forms.Control[] {this.panel1});

    this.Name = "Form1";

    this.Text = "Form1";

    this.Load += new System.EventHandler(this.Form1_Load);

    this.ResumeLayout(false);

   }

   #endregion

   /// <summary>

   /// The main entry point for the application.

   /// </summary>

   [STAThread]

   static void Main()

   {

    Application.Run(new Form1());

   }

   private void Form1_Load(object sender, System.EventArgs e)

   {

    int a=0;

    int x=0,y=0;

    for (a=0;a<=99;a++)

    {

     n[a] = new Button();

     n[a].BackColor =Color.White;

     n[a].FlatStyle = FlatStyle.Flat;

     n[a].Width = panel1.Width / 10;

     n[a].Left = x * n[a].Width;

     n[a].Height = panel1.Height / 10;

     n[a].Top = y * n[a].Height;

     n[a].Name = "b" + a;

     panel1.Controls.Add(n[a]);

     panel1.Controls[a].MouseDown += new MouseEventHandler(this.ButtonArray_OnClick);

     x += 1;

     if (x == 10)

     {

      x = 0;

      y += 1;

     }

    }

   }

   private void ButtonArray_OnClick(object sender, MouseEventArgs e)

   {

    MouseEventArgs arg=(MouseEventArgs)e;

    Button b1=(Button)sender;

    if (arg.Button==MouseButtons.Right )

    b1.BackColor=Color.White ;

    else

    {

     //b1.BackColor =Color.White ;

     b1.Image=Image.FromFile("f:\\my documents\\my pictures\\elements\\regular_smile.gif");

    }

   }

  }

}