Smile

Smile

  • 1.5k
  • 198
  • 36.1k

Datetime picker in Datagridview

Aug 8 2020 8:13 AM
I want to display a time(only HH:mm) in a column of datagridview.Below is the code which tried .The type for column is DataGridViewTextBoxColumn
 
Adding row to grid using below code
  1. private void btnAdd_Click(object sender, EventArgs e)  
  2. {  
  3. dgvDatetime.Rows.Add(1);  
  4. }  
  5. private void dgvDatetime_CellClick(object sender, DataGridViewCellEventArgs e)  
  6. {  
  7. if (e.ColumnIndex == 0)  
  8. {  
  9. //Initialized a new DateTimePicker Control  
  10. oDateTimePicker = new DateTimePicker();  
  11. //Adding DateTimePicker control into DataGridView  
  12. dgvDatetime.Controls.Add(oDateTimePicker);  
  13. // Setting the format (i.e. 2014-10-10)  
  14. oDateTimePicker.Format = DateTimePickerFormat.Custom;  
  15. oDateTimePicker.CustomFormat = "HH:mm";  
  16. oDateTimePicker.ShowUpDown = true;  
  17. // It returns the retangular area that represents the Display area for a cell  
  18. Rectangle oRectangle = dgvDatetime.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);  
  19. //Setting area for DateTimePicker Control  
  20. oDateTimePicker.Size = new Size(oRectangle.Width, oRectangle.Height);  
  21. // Setting Location  
  22. oDateTimePicker.Location = new Point(oRectangle.X, oRectangle.Y);  
  23. // An event attached to dateTimePicker Control which is fired when DateTimeControl is closed  
  24. oDateTimePicker.CloseUp += new EventHandler(oDateTimePicker_CloseUp);  
  25. // An event attached to dateTimePicker Control which is fired when any date is selected  
  26. oDateTimePicker.TextChanged += new EventHandler(dateTimePicker_OnTextChange);  
  27. // Now make it visible  
  28. oDateTimePicker.Visible = true;  
  29. }  
  30. }  
  31. private void dateTimePicker_OnTextChange(object sender, EventArgs e)  
  32. {  
  33. // Saving the 'Selected Date on Calendar' into DataGridView current cell  
  34. dgvDatetime.CurrentCell.Value = oDateTimePicker.Text.ToString();  
  35. }  
  36. void oDateTimePicker_CloseUp(object sender, EventArgs e)  
  37. {  
  38. // Hiding the control after use  
  39. oDateTimePicker.Visible = false;  
  40. }  
  41. By adding a button i am testing the value as below  
  42. private void btnget_Click(object sender, EventArgs e)  
  43. {  
  44. try  
  45. {  
  46. string _fromtime = dgvDatetime.Rows[0].Cells["ColFromTime"].Value.ToString();  
  47. }  
  48. catch (Exception ex)  
  49. {  
  50. ex.ToString();  
  51. // throw;  
  52. }  
  53. }  
By the above code i get the time only when i click in the cell and when i want to read the cell value it returns null.If and only if i click in the cell and edit the datetimepicker i can read the value of the cell.But i want to get the time in cell on adding the row to datagrid and get the value of the cell even if i dont edit the datetimepicker

Answers (2)