![](/img/trans.png)
[英]How do I write this logic of C#'s datetime difference in SQL Server?
[英]How to use c# and datasets to read/write DateTime to SQL Server
我在SQL Server中有一個表,該表具有名為datetime
名為sql_DateTime
的列。 我也有一個C#結構,它映射到該表中的一條記錄。 在此結構中是名為DateTime
m_DateTime
的成員。
我使用DataSet
從該表中檢索記錄,然后嘗試將sql_DateTime
從Dataset
到我的m_DateTime
變量中后,出現了我的m_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;
}
你說:
我在SQL Server中有一個表,該表具有名為sql_DateTime的列
但是您使用:
exp.m_DateTime = (DateTime)dsExperiments.Tables["Experiment"]
.Rows[0]["DateTime"];
注意名稱。 我很驚訝您遇到鑄造問題。 實際上,您是否有正確的名稱,但是您的行中沒有值,因此您嘗試將DBNull.Value
為DateTime
?
另外,我會說:
exp
您正在使用數據綁定嗎? 如果是這樣,您是否綁定到適當的屬性? SQL是可為空的類型嗎?
嘗試這個 :
exp.m_DateTime = DateTime.Parse(dsExperiments.Tables["Experiment"].Rows[0]["DateTime"].ToString());
問題可能是包含數據( Tables["Experiment"]
)的DataTable認為列["DateTime"]
的類型不是DateTime,而是字符串。
我認為您必須選擇:
如果您確定它始終是一個DateTime,只需對其進行解析:
exp.m_DateTime =DateTime.Parse(dsExperiments.Tables["Experiment"].Rows[0]["DateTime"].ToString());
設置dsExperiments.Tables["Experiment"].Columns["DateTime"].DataType=typeof(DateTime);
在嘗試閱讀之前。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.