我知道這是一個老問題,但我不明白爲什麼。DataGridView格式DateTime
我有2個空隙中2個按鈕結合GENERATE和SAVE:
private void btn_generate_Click(object sender, EventArgs e)
{
DateTime startdate = Convert.ToDateTime(textstarteddate.Text);
DateTime enddate = new DateTime (startdate.Year, 12, 31);
Int64 addedDays = Convert.ToInt64(textdaycount.Text);
string taskID = texttaskID.Text;
string machine = cb_machineID.Text.Trim();
string note = texttasknote.Text;
string runningtime = RMT.Text;
string period = cb_periodID.Text.Trim();
_dtdate.Columns.Add(new DataColumn("Maintenance Date", typeof(DateTime)));
_dtdate.Columns.Add(new DataColumn("TaskID", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Machine", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Note", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Period", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Running Time", typeof(String)));
_dtdate.Rows.Clear();
G1.DataBindings.Clear();
if (cb_typescheID.Text == "Fix Date")
{
do
{
_dtdate.Rows.Add(startdate.Date, taskID, machine, note, period);
startdate = startdate.AddDays(addedDays);
G1.Refresh();
//DateTime end = startdate;
}
while (startdate <= enddate);
}
G1.DataSource = _dtdate;
G1.Columns["Maintenance Date"].DefaultCellStyle.Format = "d";
}
和
private void btn_save_Click(object sender, EventArgs e)
{
if (cb_typescheID.Text == "Fix Date")
{
foreach (DataRow dr in _dtdate.Rows)
{
sqlstr = sqlstr + " INSERT INTO [PerformTask] (Year, Date, TasKID, MachineID, PerformStatus, ScheduleID, PeriodID) Values ('" + startdate.Year + "', '" + dr["Maintenance Date"].ToString() + "',";
sqlstr = sqlstr + "'" + texttaskID.Text.Trim() + "', '" + machine + "', 'RS_Open', '" + typeschedule + "', '" + period + "')";
G1.Columns["Maintenance Date"].DefaultCellStyle.Format = "d";
}
}
}
我想盡辦法把它轉換爲僅日期(DD/MM/yyyy)但它仍然顯示在DataGridView(G1)上,但是當我嘗試將它保存到SQL中的數據表中時,無論我如何轉換它,它的格式仍然是「dd/MM/yyyy hh:mm:ss tt」。我已經閱讀了關於這個問題的舊主題,嘗試了他們的方式,但仍然無法按照我想要的方式保存數據。
請幫忙。謝謝。
謝謝,它工作,只是添加信息,而不是'startdate.Date.ToString(「dd/MM/yyyy」)',你可以使用'startdate.Date.ToShortDateString()'。 – Serenade
不錯。請標記爲正確答案。再見 –