2017-01-27 50 views
-1

IM具有problam插入一個字符串,它看起來像一個日期(2015年2月23日) 從DataGridView到我的本地數據庫日期列。插入一個字符串,它看起來像一個日期到數據庫日期列

我知道我需要將我的字符串「23.02.2015」轉換爲23/02/2015,並在將它插入到我的數據庫日期列之前將其轉換爲日期變量,但是我不知道如何在我的代碼中執行該操作:

private void button3_Click(object sender, EventArgs e) 
    { 

      foreach (DataGridViewRow row in dataGridView1.Rows) 
      { 
       string constring = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\john\Documents\Visual Studio 2015\Projects\Project\Project\DB.mdf;Integrated Security=True"; 
       using (SqlConnection con = new SqlConnection(constring)) 
       { 

        using (SqlCommand cmd = new SqlCommand("INSERT INTO ResultsTable VALUES(@Date, @TagNumber)", con)) 
        { 
         cmd.Parameters.AddWithValue("@Date", row.Cells["Exposure Date"].Value); 
         cmd.Parameters.AddWithValue("@TagNumber", row.Cells["Device #"].Value); 

         cmd.ExecuteNonQuery();  
        } 


       } 
      } 

     MessageBox.Show("Records inserted."); 

    } 
總之

- 有problam IM將字符串轉換,如「2014年5月23日」的日期類型像23/05/2014,將其插入到日期列在我的數據庫在我的代碼。

+0

你要像'Convert.ToDateTime(Regex.Replace(輸入 「」, 「/」))'自動轉換爲字符串日期時間插入之前? –

+0

是的!但在我的代碼中插入這條線以適應? – shlezz

回答

1

如果你的字符串日期總是在給定的格式,這可能做的伎倆爲您服務。 DateTime.ParseExact使用指定的格式和文化特定的格式信息,將日期和時間的指定字符串表示形式轉換爲其DateTime等效形式。字符串表示的格式必須完全匹配指定的格式。

string smdt = row.Cells["Exposure Date"].Value; 
//This is the string format which is going to parse the Date 
string format = "dd.MM.yyyy"; 
DateTime dt = DateTime.ParseExact(smdt, format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal); 

然後

cmd.Parameters.AddWithValue("@Date", dt); 
+0

謝謝!現在工作正常! – shlezz

+0

樂意幫忙@shlezz :)快樂編碼好評 –

-1

請嘗試以下代碼:

string stringDate = "23.02.2015"; // Hold your string date here (row.Cells["Exposure Date"].Value) 
DateTime date = DateTime.ParseExact(stringDate, "dd.MM.yyyy", CultureInfo.InvariantCulture); 

這將您的字符串日期(stringDate)轉換爲datetime(日期)對象,你可以通過這個date object to stored procedure parameter。

我相信,你總是獲取字符串日期在這個(「DD.MM.YYYY」)格式。否則,您需要根據字符串格式進行更改。

請讓我知道這是否有幫助。

+0

與我的回答有什麼不同? –

+0

我剛剛看到,你發佈了同樣的答案。此外,大約7-8分鐘前我的。所以,思考很簡單..我只是修改了你的答案並重新發布。 但請相信我我的朋友,這是不是這樣的..實際上,當我發現這個問題..有沒有一個統一的答案,但我把它超過10分鐘(不知道,但可能有一個Skype通話是時間)張貼我的答案,沒有刷新窗口,然後我今天看到這個。 對不起。 –

相關問題