views:

542

answers:

2

How to show a Time-picker column in DataGridView?

I don't need to pick Date. I only need time to be selected.

+1  A: 

AFAIK, there is a direct way to do this. I think the only way is by creating a Custom DataGridview column. Check this link for creating a custom datagridview column

Anuraj
+2  A: 

Actually, there is a better way than creating a custom DataGridView column. What I currently do for my application is when the TIMESTAMP column of my DataGridView is entered, I position a DateTimePicker control directly over the cell. When the user has clicked out of the cell (thus confirming his selection), the DateTimePicker Visible is set to False and the DateTimePicker's value is put into the cell. By default, the DateTimePicker control Visibility is set to False until I need it. I also use this for ComboBox controls on regular cells where the user cannot enter a custom value and has to use the list of items from the Setup Screen. This technique is great for faking it. I don't have the code readily available, but it is less code and easier to maintain IMHO.

The above and following technique was taken from Faking alternative controls within a DataGridView control in Win Forms 2.0

Edit: Here is the code -

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
            if (selectAllToolStripMenuItem.Checked)
                selectAllToolStripMenuItem.Checked = false;

            if (dtPicker.Visible)
                dtPicker.Visible = false;

            if (e.ColumnIndex >= 0)
            {
                if (dataGridView1.Columns[e.ColumnIndex].Name == "Delete")
                {
                    if (adminIsLoggedIn)
                    {
                        removeRow(e);
                    }
                    else
                    {
                        MessageBox.Show("You must be logged in as an Administrator in order to change the facility configuration.", "Delete Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else if (dataGridView1.Columns[e.ColumnIndex].Name == "TIMESTAMP")
                {
                    if (adminIsLoggedIn)
                    {
                        setNewCellDate(e);
                    }
                }
                .....
            }
            // ---

}

private void setNewCellDate(DataGridViewCellEventArgs e)
{
            dtPicker.Size = dataGridView1.CurrentCell.Size;
            dtPicker.Top = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Top + dataGridView1.Top;
            dtPicker.Left = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Left + dataGridView1.Left;
            if (!(object.Equals(Convert.ToString(dataGridView1.CurrentCell.Value), "")))
                dtPicker.Value = Convert.ToDateTime(dataGridView1.CurrentCell.Value);
            dtPicker.Visible = true;
}
0A0D