首页 > 代码库 > C# DataTable的詳細使用方法

C# DataTable的詳細使用方法

在项目中经经常使用到DataTable,假设DataTable使用得当,不仅能使程序简洁有用,并且可以提高性能,达到事半功倍的效果,现对DataTable的使用技巧进行一下总结。 

       一、DataTable简单介绍    

          (1)构造函数 
          DataTable()  
不带參数初始化DataTable类的新实例。 
          DataTable(string tableName) 
用指定的表名初始化DataTable类的新实例。 
          DataTable(string tableName, string tableNamespace)
用指定的表名和命名空间初始化DataTable类的新实例。 
          (2)
经常使用属性 
          CaseSensitive   
指示表中的字符串比較是否区分大写和小写。 
          ChildRelations  
获取此DataTable的子关系的集合。 
          Columns            
获取属于该表的列的集合。 
          Constraints       
获取由该表维护的约束的集合。 
          
DataSet              获取此表所属的DataSet 
          DefaultView      
获取可能包含筛选视图或游标位置的表的自己定义视图。 
          
HasErrors         获取一个值,该值指示该表所属的DataSet的不论什么表的不论什么行中是否有错误。 
          MinimumCapacity 
获取或设置该表最初的起始大小。该表中行的最初起始大小。默认值为 50 
          Rows                 
获取属于该表的行的集合。 
          
TableName      获取或设置DataTable的名称。 

          (3)经常用法 
          AcceptChanges()  
提交自上次调用AcceptChanges()以来对该表进行的全部更改。 
          BeginInit()        
開始初始化在窗口上使用或由还有一个组件使用的DataTable。初始化发生在执行时。

          Clear()              清除全部数据的DataTable 
          Clone()             
克隆DataTable的结构,包含全部DataTable架构和约束。 
          EndInit()           
结束在窗口上使用或由还有一个组件使用的DataTable的初始化。初始化发生在执行时。 
          ImportRow(DataRow row)   
DataRow拷贝到DataTable中,保留不论什么属性设置以及初始值和当前值。 
          Merge(DataTable table) 
将指定的DataTable与当前的DataTable合并。 
          NewRow()        
创建与该表具有同样架构的新DataRow
 
       
二、DataTable使用技巧

     1Create a DataTable
         DataTable dt = new DataTable("Table_AX"); 

     2Add columns for DataTable
        //Method 1
        dt.Columns.Add("column0", System.Type.GetType("System.String"));
        //Method 2
        DataColumn dc = new DataColumn("column1", System.Type.GetType("System.Boolean"));
        dt.Columns.Add(dc); 

      
3Add rows for DataTable
         //Initialize the row
         DataRow dr = dt.NewRow();
         dr["column0"] = "AX";
         dr["column1"] = true;
         dt.Rows.Add(dr);
         //Doesn‘t initialize the row
         DataRow dr1 = dt.NewRow();
         dt.Rows.Add(dr1);  

       4Select row
         //Search the second row
假设没有赋值,则用is nullselect
         DataRow[] drs = dt.Select("column1 is null");
         DataRow[] drss = dt.Select("column0 = ‘AX‘"); 

       5Copy DataTable include data
         DataTable dtNew = dt.Copy(); 

       
6Copy DataTable only scheme
         DataTable dtOnlyScheme = dt.Clone(); 

       
7Operate one row
         //
dt的操作
         //Method 1
         DataRow drOperate = dt.Rows[0];
         drOperate["column0"] = "AXzhz";
         drOperate["column1"] = false;
         //Method 2
         drOperate[0] = "AXzhz";
         drOperate[1] = false;
         //Method 3
         dt.Rows[0]["column0"] = "AXzhz";
         dt.Rows[0]["column1"] = false;
         //Method 4
         dt.Rows[0][0] = "AXzhz";
         dt.Rows[0][1] = false; 

      
8Evaluate another DataTable‘s row to current Datatable
         dtOnlyScheme.Rows.Add(dt.Rows[0].ItemArray); 

      
9Convert to string
         System.IO.StringWriter sw = new System.IO.StringWriter();
         System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(sw);
         dt.WriteXml(xw);
         string s = sw.ToString();

       
10Filter DataTable
         dt.DefaultView.RowFilter = "column1 <> true";
         dt.DefaultView.RowFilter = "column1 = true";

       
11Sort row
          dt.DefaultView.Sort = "ID ,Name ASC";
          dt=dt.DefaultView.ToTable();

        
12Bind DataTable
           //
绑定的事实上是DefaultView
          gvTestDataTable.DataSource = dt;
          gvTestDataTable.DataBind();

        
13judge the DataTables Column name is a string
          //
推断一个字符串是否为DataTable的列名
         dtInfo.Columns.Contains("AX");

        
14DataTable convert to XML and XML convert to DataTable
          protected void Page_Load(object sender, EventArgs e)
          {
             DataTable dt_AX = new DataTable();
             //dt_AX.Columns.Add("Sex", typeof(System.Boolean));
             //DataRow dr = dt_AX.NewRow();
             //dr["Sex"] = true;
             //dt_AX.Rows.Add(dr);
             string xml=ConvertBetweenDataTableAndXML_AX(dt_AX);
             DataTable dt = ConvertBetweenDataTableAndXML_AX(xml);
         }
         public string ConvertBetweenDataTableAndXML_AX(DataTable dtNeedCoveret)
        {
             System.IO.TextWriter tw = new System.IO.StringWriter();
             //if TableName is empty, WriteXml() will throw Exception.                 

dtNeedCoveret.TableName=dtNeedCoveret.TableName.Length==0?"Table_AX":dtNeedCoveret.TableName;
             dtNeedCoveret.WriteXml(tw);
             dtNeedCoveret.WriteXmlSchema(tw);
             return tw.ToString();
        }
         public DataTable ConvertBetweenDataTableAndXML_AX(string xml)
        {
             System.IO.TextReader trDataTable = new System.IO.StringReader(xml.Substring(0, xml.IndexOf("<?xml")));
             System.IO.TextReader trSchema = new System.IO.StringReader(xml.Substring(xml.IndexOf("<?xml")));
             DataTable dtReturn = new DataTable();
             dtReturn.ReadXmlSchema(trSchema);
             dtReturn.ReadXml(trDataTable);
             return dtReturn;
        }

 

C# DataTable的詳細使用方法