C# DataTable的詳細用法

來源:互聯網
上載者:User
C# DataTable的詳細用法 http://blog.csdn.net/hcw_peter/article/details/3980723 

在項目中經常用到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。DataSet相關資訊,可見我以前的一篇文章《資料訪問(2)-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提示

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

      (2)Add 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); 

       (3)Add 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);  

        (4)Select row
         //Search the second row 如果沒有賦值,則用is null來select
         DataRow[] drs = dt.Select("column1 is null");
         DataRow[] drss = dt.Select("column0 = 'AX'"); 

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

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

        (7)Operate 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; 

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

       (9)Convert 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();

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

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

         (12)Bind DataTable
           //綁定的其實是DefaultView
          gvTestDataTable.DataSource = dt;
          gvTestDataTable.DataBind();

         (13)judge the DataTable’s Column name is a string
          //判斷一個字串是否為DataTable的列名
         dtInfo.Columns.Contains("AX");

         (14)DataTable 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;
        }

 

 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.