C# 控件的属性是个类,如何给添加自定义属性
作者:C/S框架网  发布日期:2011/05/09 12:20:50
C# 控件的属性是个类,如何给添加自定义属性


 

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections;
using System.Windows.Forms;

namespace CSFramework.Tech2011
{
   
   /// <summary>
   /// 组合模式演示,将DataTable.Rows由构造器传入。
   /// </summary>
   public class MyDataRows
   {
      private DataRowCollection _rows;
      
      //将DataTable.Rows由构造器传入。
      public MyDataRows(DataRowCollection rows)
      {
         _rows = rows;
      }
      
      //设计一个自定义的方法.
      public DataRow FindRowByFieldValue(string fieldName, string value)
      {
         foreach (DataRow row in _rows)
         {
            if (row[fieldName].ToString().ToUpper() == value.ToUpper())
            return row;
         }
         
         return null;
      }
      
   }
   
   /// <summary>
   /// 自定义DataTable
   /// </summary>
   public class MyDataTable : DataTable
   {
      public MyDataTable()
      {
         _MyRows = new MyDataRows(this.Rows);
      }
      
      private MyDataRows _MyRows = null;
      public MyDataRows MyRows { get { return _MyRows; } }
   }
   
   /// <summary>
   /// 测试用的类
   /// </summary>
   public class vjsdn_Composite
   {
      public void Test()
      {
         //创建一个自己的类
         MyDataTable dt = new MyDataTable();
         dt.Columns.Add("user_id", typeof(string));
         dt.Columns.Add("user_name", typeof(string));
         
         //增加两条测试记录
         DataRow row;
         row = dt.NewRow();
         row["user_id"] = "001";
         row["user_name"] = "csdn";
         dt.Rows.Add(row);
         
         row = dt.NewRow();
         row["user_id"] = "002";
         row["user_name"] = "vjsdn";
         dt.Rows.Add(row);
         
         //注意这里(MyRows属性及FindRowByFieldValue方法)。调用自定义的方法!
         DataRow yes = dt.MyRows.FindRowByFieldValue("user_name", "csdn");
         if (yes != null)
         {
            MessageBox.Show(yes["user_name"].ToString());
         }
         else
         {
            MessageBox.Show("没找到!!!");
         }
         
      }
   }
}

上一篇 下一篇