日期時間和字串如何轉換? 如果沒有時間,DateTimePicker如何顯示空白?

日期時間和字串如何轉換? 如果沒有時間,DateTimePicker如何顯示空白?

- 將DateTimePicker的值(日期時間)轉為字串 :
  string myDate = myDateTimePicker.Value.ToString("yyyyMMdd");
  string myDateTime = myDateTimePicker.Value.ToString("yyyyMMddHHmmss");

- 將系統時間轉字串
  string myDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");

- 將字串轉為DateTimePicker的值(日期時間):
  myDateTimePicker.Value = DateTime.Parse(myDateTimeString);

- DateTimePicker如何顯示特定的日期格式:
  myDateTimePicker.CustomFormat = "yyyy-MM-dd HH:mm:ss";
  myDateTimePicker.Value = DateTime.Parse(myDateTimeString);

 - 如果沒有時間,DateTimePicker如何顯示空白?
  myDateTimePicker.CustomFormat = " ";
  myDateTimePicker.Format = DateTimePickerFormat.Custom;

- 一個範例程式:

//the myDateTimeString is a string.
//the myDateTimePicker is a DateTimePicker control

if (myDateTimeString.Length == 14)
{
    //if myDateTimeString is not blank; ex, myDateTimeString = "20190125153050"
    myDateTimeString = myDateTimeString.Substring(0, 4) + "-" + myDateTimeString.Substring(4, 2) + "-" + myDateTimeString.Substring(6, 2) 
   + " " + 
   myDateTimeString.Substring(8, 2) + ":" + myDateTimeString.Substring(10, 2) + ":" + myDateTimeString.Substring(12, 2);
    myDateTimePicker.CustomFormat = "yyyy-MM-dd HH:mm:ss";
    myDateTimePicker.Value = DateTime.Parse(myDateTimeString);
}
else
{
    //if myDateTimeString is empty, make the column show blank.
    myDateTimePicker.CustomFormat = " ";
    myDateTimePicker.Format = DateTimePickerFormat.Custom;
}

Read More »

為什麼要(如何去)修改DataSet/DataTable的資料列狀態(RowState)?

- Dataset裡面的每一筆紀錄就是DataRow,每筆 DataRow 物件都有其 RowState 屬性(RowState有五種屬性,分別是Unchanged、Added、Modified、Deleted、Detached)。

- 當我們用DbDataAdapter.Update這個方法來更新Dataset的的紀錄時,它會根據Rowstate的值來做INSERT、UPDATE 或 DELETE。

但是在程式執行過程中,如果這個Dataset和(1)Datagridview或Textbox等控件做Binding時或(2)新增一個欄位時,它的RowState也會被改變。

所以為了DbDataAdapter.Update能正確更新使用者修改的紀錄,執行綁訂或新增欄位後需要將Dataset所有的紀錄的RowState恢復為UnChanged,以下程式可以達成此需求:

A. 針對單一Table :
internal static bool changeRowStateToUnchanged4Table(DataTable myTable)
{
    bool verify = false;            
    try
    {
        foreach (DataRow dr in myTable.Rows)
        {
            if (dr.RowState != DataRowState.Unchanged)
                dr.AcceptChanges();
        }               
        verify = true;
    }
    catch (Exception)
    {
        verify = false;
    }
    return verify;
}
B 針對所有的Table:
internal static bool changeRowStateToUnchanged4Dataset(DataSet myDataset)
{
    bool verify = false;
    try
    {
        foreach (DataTable table in myDataset.Tables)
        {
            foreach (DataRow dr in table.Rows)
            {
                if (dr.RowState != DataRowState.Unchanged)
                    dr.AcceptChanges();
            }
        }
        verify = true;
    }
    catch (Exception)
    {
        verify = false;
    }
    return verify;
}

- 參考資料 : 資料列狀態和資料列版本

Read More »
>