2017-03-06 104 views
0

Sql Server的變量TEST_TIME數據類型爲Time(7)
我在C#中創建了表,並且它自動分配了Timespan數據類型。
現在,我試圖上傳csv文件數據到SQL數據庫,它給我一個錯誤「不能隱式地將DateTime轉換爲Timespan」。解決這個問題的最好方法是什麼? 用戶首先選擇的CSV文件:無法將DateTime隱式轉換爲Timespan

private void button8_Click(object sender, EventArgs e) 
     { 
       try 
        { 
         using (OpenFileDialog openfiledialog1 = new OpenFileDialog() 
         {Filter = "Excel Workbook 97-2003|*.xls|Excel Workbook|*.xlsx|Excel Workbook|*.xlsm|Excel Workbook|*.csv|Excel Workbook|*.txt", ValidateNames = true })      
         { 
--After some IFs-- 

    else if (openfiledialog1.FilterIndex == 4) 
           { 

            DataTable oDataTable = null; 
            int RowCount = 0; 
            string[] ColumnNames = null; 
            string[] oStreamDataValues = null; 
            //using while loop read the stream data till end 
            while (!oStreamReader.EndOfStream) 
            { 
             String oStreamRowData = oStreamReader.ReadLine().Trim(); 
             if (oStreamRowData.Length > 0) 
             { 
              oStreamDataValues = oStreamRowData.Split(','); 
              //Bcoz the first row contains column names, we will populate 
              //the column name by 
              //reading the first row and RowCount-0 will be true only once 
              if (RowCount == 0) 
              { 
               RowCount = 1; 
               ColumnNames = oStreamRowData.Split(','); 
               oDataTable = new DataTable(); 

               //using foreach looping through all the column names 
               foreach (string csvcolumn in ColumnNames) 
               { 
                DataColumn oDataColumn = new DataColumn(csvcolumn.ToUpper(), typeof(string)); 

                //setting the default value of empty.string to newly created column 
                oDataColumn.DefaultValue = string.Empty; 

                //adding the newly created column to the table 
                oDataTable.Columns.Add(oDataColumn); 
               } 
              } 
              else 
              { 
               //creates a new DataRow with the same schema as of the oDataTable    
               DataRow oDataRow = oDataTable.NewRow(); 

               //using foreach looping through all the column names 
               for (int i = 0; i < ColumnNames.Length; i++) 
               { 
                oDataRow[ColumnNames[i]] = oStreamDataValues[i] == null ? string.Empty : oStreamDataValues[i].ToString(); 
               } 

               //adding the newly created row with data to the oDataTable  
               oDataTable.Rows.Add(oDataRow); 
              } 
             } 
            } 
            result.Tables.Add(oDataTable); 
            //close the oStreamReader object 
            oStreamReader.Close(); 
            //release all the resources used by the oStreamReader object 
            oStreamReader.Dispose(); 
            dataGridView5.DataSource = result.Tables[oDataTable.TableName]; 
           } 

這裏是代碼:

private void button9_Click(object sender, EventArgs e) 
      { 

       try 
       {    


        DataClasses1DataContext conn = new DataClasses1DataContext(); 
     else if (textBox3.Text.Contains("GEN_EX")) 
      { 
       foreach (DataTable dt in result.Tables) 
       { 
        foreach (DataRow dr in dt.Rows) 
        { 
         GEN_EX addtable = new GEN_EX() 
         { 

          EX_ID = Convert.ToByte(dr[0]), 
          DOC_ID = Convert.ToByte(dr[1]), 
          PATIENT_NO = Convert.ToByte(dr[2]), 
          TEST_DATE = Convert.ToDateTime(dr[3]),      
          **TEST_TIME = Convert.ToDateTime((dr[4])),** 

         }; 
         conn.GEN_EXs.InsertOnSubmit(addtable); 
        } 
       } 
       conn.SubmitChanges(); 
       MessageBox.Show("File uploaded successfully"); 
      } 
    else 
     { 
      MessageBox.Show("I guess table is not coded yet"); 
     } 
} 

EDIT

的TEST_TIME表示HH:MM:SS
類型化的數據集是定義爲:

public virtual int Update(
        byte EX_ID, 
        byte DOC_ID, 
        byte PATIENT_NO, 
        System.DateTime TEST_DATE, 
        System.TimeSpan TEST_TIME) 
+2

做一個'博士[4] .GetType()',看看是什麼返回'包含在'DataRow' – xanatos

+0

類型dt.Columns [4] .DataType'屬性? – bradbury9

+0

你試圖將哪些數據放入該列中? (即csv中它不喜歡的值是什麼) –

回答

2

根據您的輸入,dr[4]代表hours:minutes:seconds格式的時間值,我建議您採用以下解決方案。

private TimeSpan GetTimeSpan(string timeString) 
{ 
    var timeValues = timeString.Split(new char[] { ':' }); 
    //Assuming that timeValues array will have 3 elements. 
    var timeSpan = new TimeSpan(Convert.ToInt32(timeValues[0]), Convert.ToInt32(timeValues[1]), Convert.ToInt32(timeValues[2])); 
    return timeSpan; 
} 

使用上述方法如下。

else if (textBox3.Text.Contains("GEN_EX")) 
{ 
    foreach (DataTable dt in result.Tables) 
    { 
     foreach (DataRow dr in dt.Rows) 
     { 
      GEN_EX addtable = new GEN_EX() 
      { 

       EX_ID = Convert.ToByte(dr[0]), 
       DOC_ID = Convert.ToByte(dr[1]), 
       PATIENT_NO = Convert.ToByte(dr[2]), 
       TEST_DATE = Convert.ToDateTime(dr[3]),      
       **TEST_TIME = GetTimeSpan(dr[4].ToString()),** 

      }; 
      conn.GEN_EXs.InsertOnSubmit(addtable); 
     } 
    } 
    conn.SubmitChanges(); 
    MessageBox.Show("File uploaded successfully"); 
} 

這應該給你你想要的價值。如果dr[4]的值不是hours:minutes:seconds格式,您將面臨運行時問題。我會把它留給你。

+0

錯誤'System.Data.DataRow'沒有包含'GetString'的定義,也沒有找到接受'System.Data.DataRow'類型的第一個參數的擴展方法'GetString'(你是否缺少一個using指令或彙編參考?)\t 我得到這個 – SQLserving

+0

的編譯錯誤哦...我現在意識到了...我已經改變了答案....現在應該不會有任何錯誤... –

0

首先Timespan和DateTime是2個不同類型,沒有隱式轉換可用。由於Timespan是兩個DateTime之間的時間值,因此您需要知道用於啓動Timespan的Mesure的引用時間(DateTime)。

例如,它可能是從DateTime dtReferential = new DateTime(1900, 01, 01);

爲了讓你需要給它一個C#時間跨度一個SQL時間跨度值!將TEST_TIME值更改爲Timespan。最後,給它的參考時間的減價值。

使用前面的例子:

else if (textBox3.Text.Contains("GEN_EX")) 
{ 
    foreach (DataTable dt in result.Tables) 
    { 
     foreach (DataRow dr in dt.Rows) 
     { 
      GEN_EX addtable = new GEN_EX() 
      { 

       EX_ID = Convert.ToByte(dr[0]), 
       DOC_ID = Convert.ToByte(dr[1]), 
       PATIENT_NO = Convert.ToByte(dr[2]), 
       TEST_DATE = Convert.ToTimespan(dr[3]),      
       TEST_TIME = dtReferential.Subtract(Convert.ToDateTime(dr[4])) 

      }; 
      conn.GEN_EXs.InsertOnSubmit(addtable); 
     } 
    } 
    conn.SubmitChanges(); 
    MessageBox.Show("File uploaded successfully"); 
} 
相關問題