TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Smile
1.5k
198
36.5k
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
private
void
btnAdd_Click(
object
sender, EventArgs e)
{
dgvDatetime.Rows.Add(1);
}
private
void
dgvDatetime_CellClick(
object
sender, DataGridViewCellEventArgs e)
{
if
(e.ColumnIndex == 0)
{
//Initialized a new DateTimePicker Control
oDateTimePicker =
new
DateTimePicker();
//Adding DateTimePicker control into DataGridView
dgvDatetime.Controls.Add(oDateTimePicker);
// Setting the format (i.e. 2014-10-10)
oDateTimePicker.Format = DateTimePickerFormat.Custom;
oDateTimePicker.CustomFormat =
"HH:mm"
;
oDateTimePicker.ShowUpDown =
true
;
// It returns the retangular area that represents the Display area for a cell
Rectangle oRectangle = dgvDatetime.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex,
true
);
//Setting area for DateTimePicker Control
oDateTimePicker.Size =
new
Size(oRectangle.Width, oRectangle.Height);
// Setting Location
oDateTimePicker.Location =
new
Point(oRectangle.X, oRectangle.Y);
// An event attached to dateTimePicker Control which is fired when DateTimeControl is closed
oDateTimePicker.CloseUp +=
new
EventHandler(oDateTimePicker_CloseUp);
// An event attached to dateTimePicker Control which is fired when any date is selected
oDateTimePicker.TextChanged +=
new
EventHandler(dateTimePicker_OnTextChange);
// Now make it visible
oDateTimePicker.Visible =
true
;
}
}
private
void
dateTimePicker_OnTextChange(
object
sender, EventArgs e)
{
// Saving the 'Selected Date on Calendar' into DataGridView current cell
dgvDatetime.CurrentCell.Value = oDateTimePicker.Text.ToString();
}
void
oDateTimePicker_CloseUp(
object
sender, EventArgs e)
{
// Hiding the control after use
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();
// throw;
}
}
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
Reply
Answers (
2
)
How do we combine expressions in c#.
How to Fetch and Display record in textboxes