我在SQL Server中有一个表,其名称为,其类型为datetime
。我也有一个C#结构映射到该表中的单个记录;在这个结构中是DateTime
类型的名为m_DateTime
的成员。之后我从这个表中检索记录,使用DataSet
,然后尝试获取来自Dataset
的sql_DateTime
到我m_DateTime
变量发生如何使用c#和数据集来读/写DateTime到SQL Server
我的问题。当我尝试执行类似于处理其他数据类型的方式时,我得到了一个InvalidCastException
。
我希望能够在我的GUI中使用DateTimePicker
来显示和设置日期和时间。
我的代码已附上供您参考。感谢您的任何指导。
public bool GetExperiment(ref Experiment exp, int ExperimentID, ref string statusMsg)
{
bool ret = true;
statusMsg = "GetExperiment: ";
try
{
// Open the connection
conn.Open();
// init SqlDataAdapter with select command and connection
string SelectString =
@"SELECT * " +
"FROM Experiment " +
"WHERE ExperimentID = " + ExperimentID.ToString();
SqlDataAdapter daExperiments = new SqlDataAdapter(SelectString, conn);
// fill the dataset
DataSet dsExperiments = new DataSet();
daExperiments.Fill(dsExperiments, "Experiment");
// assign dataset values to proj object that was passed in
exp.m_ExperimentID = (int)dsExperiments.Tables["Experiment"].Rows[0]["ExperimentID"];
exp.m_ProjectID = (int)dsExperiments.Tables["Experiment"].Rows[0]["ProjectID"];
exp.m_Name = (string)dsExperiments.Tables["Experiment"].Rows[0]["Name"];
exp.m_Description = (string)dsExperiments.Tables["Experiment"].Rows[0]["Description"];
exp.m_UserID = (int)dsExperiments.Tables["Experiment"].Rows[0]["UserID"];
// PROBLEM OCCURS HERE
exp.m_DateTime = (DateTime)dsExperiments.Tables["Experiment"].Rows[0]["DateTime"];
}
catch (Exception ex)
{
ret = false;
statusMsg += "Failed - " + ex.Message;
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
return ret;
}
public class Experiment
{
public int m_ExperimentID;
public int m_ProjectID;
public string m_Name;
public string m_Description;
public int m_UserID;
public DateTime m_DateTime;
}
有大量的在线文章如何将MSSQL DATETIME格式化为DateTime .NET结构。我猜你使用了错误的变量类型,并且因为这个原因他们不能被铸造。阅读此:http://stackoverflow.com/questions/1181662/is-there-any-difference-between-datetime-in-c-sharp-and-datetime-in-sql-server –