2010-02-26 44 views
4

我創建了一個數據表,並試圖通過插入該SqlBulkCopy的數據表,但不知何故它似乎並沒有爲我工作....SqlBulkCopy的似乎並沒有爲我工作

我得到了錯誤,

The given value of type DateTime from the data source cannot be converted 
to type decimal of the specified target column. 

我的數據源是,

DataTable dt = new DataTable(); 
    dt.Columns.Add(new DataColumn("EmpId", typeof(Int64))); 
    dt.Columns.Add(new DataColumn("FromDate", typeof(DateTime))); 
    dt.Columns.Add(new DataColumn("ToDate", typeof(DateTime))); 
    dt.Columns.Add(new DataColumn("DaysPresent", typeof(decimal))); 
    dt.Columns.Add(new DataColumn("OpeningAdvance", typeof(double))); 
    dt.Columns.Add(new DataColumn("AdvanceDeducted", typeof(double))); 
    dt.Columns.Add(new DataColumn("RemainingAdvance", typeof(double))); 
    dt.Columns.Add(new DataColumn("SalaryGiven", typeof(double))); 
    dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime))); 

    foreach (GridViewRow row in gridEmployee.Rows) 
    { 
     if (row.RowType == DataControlRowType.DataRow) 
     { 
      DataRow dr = dt.NewRow(); 
      dr["EmpId"] = Convert.ToInt64(((HiddenField)row.Cells[0].FindControl("HiddenId")).Value); 
      dr["FromDate"] = Convert.ToDateTime(GetMonthNumberFromAbbreviation(fromdate[1].ToString()) + '/' + fromdate[0].ToString() + '/' + fromdate[2].ToString()); 
      dr["ToDate"] = Convert.ToDateTime(GetMonthNumberFromAbbreviation(todate[1].ToString()) + '/' + todate[0].ToString() + '/' + todate[2].ToString()); 
      dr["DaysPresent"] = Convert.ToDecimal(((TextBox)row.Cells[3].FindControl("TxtDaysPresent")).Text); 
      dr["OpeningAdvance"] = Convert.ToDouble(((TextBox)row.Cells[4].FindControl("txtOpeningAdv")).Text); 
      dr["AdvanceDeducted"] = Convert.ToDouble(((TextBox)row.Cells[5].FindControl("TxtAdvanceDeducted")).Text); 
      dr["RemainingAdvance"] = Convert.ToDouble(((TextBox)row.Cells[6].FindControl("TxtClosingAdvance")).Text); 
      dr["SalaryGiven"] = Convert.ToDouble(((TextBox)row.Cells[7].FindControl("TxtSalary")).Text); 
      dr["CreatedDate"] = Convert.ToDateTime(System.DateTime.Now.ToString()); 
      dt.Rows.Add(dr); 
     } 
    } 
    SqlBulkCopy sbc = new SqlBulkCopy(connectionString); 
    sbc.DestinationTableName = "SalaryDetails"; 
    sbc.WriteToServer(dt); 
    sbc.Close(); 

而且我的目的地表看起來像這樣,

alt text http://img231.imageshack.us/img231/5448/mytable.jpg

+0

圖像已過期隊友 – 2015-09-21 11:35:37

回答

6

您需要指定列映射,因爲您在DataTable和目標表中沒有相同數量的列。

你可以這樣說:

sbc.ColumnMappings.Add("EmpId", "EmpId"); 
sbc.ColumnMappings.Add("FromDate", "FromDate"); 
// and so on, with the rest of the columns; and after that comes 
sbc.WriteToServer(dt); 
sbc.Close(); 
+0

@treaschf如何添加列映射? – 2010-02-26 07:24:06

+0

@treaschf'sbc.ColumnMappings.Add(「EmpId」,「EmpId」);'這就是我想要做的.. – 2010-02-26 07:26:04