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
- private void btnAdd_Click(object sender, EventArgs e)
- {
- dgvDatetime.Rows.Add(1);
- }
- private void dgvDatetime_CellClick(object sender, DataGridViewCellEventArgs e)
- {
- if (e.ColumnIndex == 0)
- {
-
- oDateTimePicker = new DateTimePicker();
-
- dgvDatetime.Controls.Add(oDateTimePicker);
-
- oDateTimePicker.Format = DateTimePickerFormat.Custom;
- oDateTimePicker.CustomFormat = "HH:mm";
- oDateTimePicker.ShowUpDown = true;
-
- Rectangle oRectangle = dgvDatetime.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
-
- oDateTimePicker.Size = new Size(oRectangle.Width, oRectangle.Height);
-
- oDateTimePicker.Location = new Point(oRectangle.X, oRectangle.Y);
-
- oDateTimePicker.CloseUp += new EventHandler(oDateTimePicker_CloseUp);
-
- oDateTimePicker.TextChanged += new EventHandler(dateTimePicker_OnTextChange);
-
- oDateTimePicker.Visible = true;
- }
- }
- private void dateTimePicker_OnTextChange(object sender, EventArgs e)
- {
-
- dgvDatetime.CurrentCell.Value = oDateTimePicker.Text.ToString();
- }
- void oDateTimePicker_CloseUp(object sender, EventArgs e)
- {
-
- oDateTimePicker.Visible = false;
- }
- By adding a button i am testing the value as below
- private void btnget_Click(object sender, EventArgs e)
- {
- try
- {
- string _fromtime = dgvDatetime.Rows[0].Cells["ColFromTime"].Value.ToString();
- }
- catch (Exception ex)
- {
- ex.ToString();
-
- }
- }
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