我有datagridview并使用这些代码在数据库中更新。 但我在datagridview中更新日期时遇到问题 我的列日期是(ra8,ra9) 我尝试更新时会出现这些错误
从字符串转换日期和/或时间时转换失败。
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(cs.DBConn);
foreach (DataGridViewRow dgRow in dgw.Rows)
{
string Id = dgRow.Cells[0].Value.ToString();
string Id2 = dgRow.Cells[1].Value.ToString();
string isEdit2 = dgRow.Cells[2].Value.ToString();
string isEdit = dgRow.Cells[3].Value.ToString();
string isDelete = dgRow.Cells[4].Value.ToString();
string isADD = dgRow.Cells[5].Value.ToString();
string isADD1 = dgRow.Cells[6].Value.ToString();
string isADD2 = dgRow.Cells[7].Value.ToString();
string isADD3 = dgRow.Cells[8].Value.ToString();
DateTime isADD4 =Convert.ToDateTime( dgRow.Cells[9].Value.ToString());
DateTime isADD5 =Convert.ToDateTime( dgRow.Cells[10].Value.ToString());
string isADD6 = dgRow.Cells[11].Value.ToString();
string cb = "update ma3 set ra1='" + Id2 + "', ra2='" + isEdit2 + "', ra3='" + isEdit + "', ra4='" + isDelete + "', ra5='" + isADD + "', ra6='" + isADD1 + "', ra7='" + isADD2 + "', ra8='" + isADD3 + "', ra9='" + isADD4 + "', ra10='" + isADD5 + "', ra11='" + isADD6 + "' where id='" + Id + "'";
con.Open();
cmd = new SqlCommand(cb);
cmd.Connection = con;
cmd.ExecuteReader();
con.Close();
}
}
答案 0 :(得分:3)
不要使用Convert.ToDateTime
,请使用DateTime.TryParseExact;
并将字符串转换为日期时间。
使用TryParseExact
与您的合成器一起工作,这样您的程序就不会因异常而失败,而是可以通过bool值安全地检查转换是否完成
string datestr = "26/12/2017 12:00:00 am";
DateTime test = DateTime.Now;
if( DateTime.TryParseExact(datestr, "dd/MM/yyyy hh:mm:ss tt", null,
System.Globalization.DateTimeStyles.None, out test))
{
//insert in db or proceed with input
}
else
{
//log and provide error message
}
答案 1 :(得分:0)
private void button1_Click(object sender, EventArgs e)
{ con = new SqlConnection(cs.DBConn);
foreach (DataGridViewRow dgRow in dgw.Rows)
{
string id = dgRow.Cells[0].Value.ToString();
string date = dgRow.Cells[1].Value.ToString();
DateTime test;
string cb = "update date set date='" + DateTime.TryParseExact(date, "dd/MM/yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out test) + "' where id='" + id + "'";
con.Open();
cmd = new SqlCommand(cb);
cmd.Connection = con;
cmd.ExecuteReader();
con.Close();
}
}
好的,我尝试这些代码,这些消息显示正常转换失败时从字符串转换日期和/或时间。