datetime
이라는 sql_DateTime
열이있는 SQL Server 테이블이 있습니다. 또한이 테이블의 단일 레코드에 매핑되는 C# 구조가 있습니다. 이 구조에서 DateTime
유형의 m_DateTime
이라는 구성원이 있습니다. 나는,이 테이블에서 레코드를 검색 DataSet
을 사용하고 내 m_DateTime
변수에 Dataset
에서 sql_DateTime
를 얻을려고 후C# 및 datasets를 사용하여 SQL Server에 DateTime을 읽거나 쓰는 방법
내 문제가 발생합니다. 다른 데이터 유형을 처리하는 방식과 비슷하게하려고하면 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 –