簡體   English   中英

手動輸入日期或時間時,C#運行時DateTimePicker驗證錯誤?

[英]C# run-time DateTimePicker validation error when manually entering date or time?

我有一個針對帶有兩個DataGridViews的.NET 3.5的C#WinForms項目。 Win 7 64位上的Visual Studio 2010 Pro。

我正在使用在運行時創建的兩個DateTimePicker控件(一個用於時間,一個用於日期),這些控件浮動在gridview中適當的DateTime單元格上。 僅當時間或日期單元格成為焦點時才顯示選擇器。

系統時間格式為24小時。

private DateTimePicker timePicker;

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH:mm";
timePicker.MaxDate = new DateTime(9998, 12, 31);
timePicker.MinDate = new DateTime(1753, 01, 01);
timePicker.ShowUpDown = true;
timePicker.Width = 60;
timePicker.Hide();
timePicker.ValueChanged += new EventHandler(timePicker_ValueChanged);
timePicker.KeyPress += new KeyPressEventHandler(timePicker_KeyPress);
timePicker.LostFocus += new EventHandler(timePicker_LostFocus);
dgTxSummary.Controls.Add(timePicker);

void timePicker_ValueChanged(object sender, EventArgs e)
{
   // dgTxSummary is the DataGridView containing the dates and times
   dgTxSummary.CurrentCell.Value = timePicker.Value;            
}

void timePicker_LostFocus(object sender, EventArgs e)
{
   timePicker.Hide();
}

// Used for debugging; shows a message in a text field when 10, 20 etc
// where entered
void timePicker_KeyPress(object sender, KeyPressEventArgs e)
{
   if (Char.IsDigit(prevChar) && e.KeyChar == '0')
   {
      string correctHour = prevChar.ToString() + '0';
      Message = "Should have been " + correctHour;
   }

   prevChar = e.KeyChar;
}

單擊時間單元時,將顯示時間選擇器

private void ShowTimePicker(Point cellPos, DateTime dt)
{
  timePicker.Location = cellPos;
  timePicker.Value = dt;
  timePicker.Show();
  timePicker.Focus();
}

僅當滿足兩個條件時,才會出現此問題:

1)選擇器獲得焦點后第一次輸入數字
2)手動輸入一個以0 *結尾的有效數字(鍵盤)

*小時插槽中的0、10或20,分鍾插槽中的0、10,...,50

使用上下按鈕可以正常工作。

結果是, 首先顯示了上一個時間或日期,並且上拉按鈕消失了,控件(時間選擇器)被隱藏或關閉,並且datagridview中的基礎單元格具有焦點,並處於與上一個時間或日期一起的編輯模式。 在單元格內部或外部單擊時,如果輸入10,則顯示01。

我已經在相同的表單上創建了一個設計時datetimepicker,它可以正常工作。

我想念什么?

我終於在代碼中找到了罪魁禍首:

dgTxSummary.Controls.Add(timePicker);

似乎需要將DateTimePicker添加到表單中 ,而不是DataGridView中

將代碼更改為this.Controls.Add(timePicker); 並使用datePicker.BringToFront(); ShowTimePicker(...) (為避免將控件隱藏在DataGridView后面),一切都很好:-)

FWIW我使用以下代碼將DateTimePicker放置在相應單元格的頂部(去除了錯誤處理,空值檢查等的代碼):

private void dgTxSummary_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    Rectangle cellRect = dgTxSummary.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
    Point dgPos = dgTxSummary.Location;
    Point cellPos = new Point(dgPos.X + cellRect.X, dgPos.Y + cellRect.Y);

    DateTime dt = DateTime.Parse(row.Cells[e.ColumnIndex].FormattedValue.ToString());

    ShowDatePicker(cellPos, dt);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM