将 varchar 数据类型转换为 datetime 数据类型导致值超出范围错误
我正在尝试使用表单将数据输入到我的表中,表单验证和 sql server 中的日期格式都是 dd/mm/yy,但是当我尝试从表单提交数据时高于 12(例如 13/12/2012)它抛出一个异常,其原因是“将 varchar 数据类型转换为 datetime 数据类型导致值超出范围错误”,如果我尝试输入数据以 mm/dd/yy 格式进入表格,它指出“错误的日期格式”,这意味着 dd/mm/yy 格式是正确的格式
下面是我的表单代码:
private void btnAddProject_Click(object sender, EventArgs e)
{
DateTime startDate;
DateTime endDate;
if (txtProjectName.Text == "") //client side validation
{
MessageBox.Show("Enter Project Name");
return;
}
try
{
startDate = DateTime.Parse(txtProjectStart.Text);
endDate = DateTime.Parse(txtProjectEnd.Text);
}
catch (Exception)
{
MessageBox.Show("Wrong Date Format");
return;
}
fa.CreateProject(txtProjectName.Text, startDate, endDate, (int)cbCustomers.SelectedValue, ptsUser.Id);
txtProjectName.Text = "";
txtProjectStart.Text = "";
txtProjectEnd.Text = "";
cbCustomers.SelectedIndex = 0;
MessageBox.Show("Project Created");
adminControl.SelectTab(2);
}// end btnAddProject
这是我的 DAO 中的代码:
public void CreateProject(string name, DateTime startDate, DateTime endDate, int customerId, int administratorId)
{
string sql;
SqlConnection cn;
SqlCommand cmd;
Guid projectId = Guid.NewGuid();
sql = "INSERT INTO Project (ProjectId, Name, ExpectedStartDate, ExpectedEndDate, CustomerId, AdministratorId)";
sql += String.Format("VALUES('{0}', '{1}', '{2}', '{3}', {4}, {5})", projectId, name, startDate, endDate, customerId, administratorId);
cn = new SqlConnection(Properties.Settings.Default.WM75ConnectionString);
cmd = new SqlCommand(sql, cn);
try
{
cn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw new Exception("Error Creating Project", ex);
}
finally
{
cn.Close();
}
}//end CreateProject Method
这是我的门面代码:
public void CreateProject(string name, DateTime startDate, DateTime endDate, int customerId, int administratorId)
{
dao.CreateProject(name, startDate, endDate, customerId, administratorId);
}//end CreateProject
最佳答案
您可以像这样进行 sqldatetime 转换 sqldatetime
var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
关于c# - 将 varchar 数据类型转换为 datetime 数据类型导致值超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12393665/