我在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 –