2015年4月18日 星期六

[C#] DataGridView 轉成 DataTable

DataGridView轉成DataTable

  //Converts the DataGridView to DataTable  
     public static DataTable DataGridView2DataTable(DataGridView dgv, String tblName="", int minRow = 0)  
     {  
       DataTable dt = new DataTable();  
       // Header columns  
       foreach (DataGridViewColumn column in dgv.Columns)  
       {  
         //DataColumn dc = new DataColumn(column.Name.ToString());  
         DataColumn dc = new DataColumn(column.HeaderText.ToString());  
         dt.Columns.Add(dc);  
       }  
       // Data cells  
       for (int i = 0; i < dgv.Rows.Count; i++)  
       {  
         DataGridViewRow row = dgv.Rows[i];  
         DataRow dr = dt.NewRow();  
         for (int j = 0; j < dgv.Columns.Count; j++)  
         {  
           dr[j] = (row.Cells[j].Value == null) ? "" : row.Cells[j].Value.ToString();  
         }  
         dt.Rows.Add(dr);  
       }  
       // Related to the bug arround min size when using ExcelLibrary for export  
       for (int i = dgv.Rows.Count; i < minRow; i++)  
       {  
         DataRow dr = dt.NewRow();  
         for (int j = 0; j < dt.Columns.Count; j++)  
         {  
           dr[j] = " ";  
         }  
         dt.Rows.Add(dr);  
       }  
       return dt;  
     }  

沒有留言:

張貼留言