2017-01-27 34 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通话是时间)张贴我的答案,没有刷新窗口,然后我今天看到这个。 对不起。 –

相关问题