I am having an issue with the dateTimePicker class. I need to have the DateTimePicker empty on construct, which I have achieved via this:
dateTimePicker1.MaxDate = DateTime.Now; // Ensures no future dates are set.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";
My issue is that now the user has to actually click on the on the calendar to enter a date, rather than using the up down keys, or type. Is there anyway I can initialize dateTimePicker1 to " " as I have in my constructor, but also allow the user to 'Activate' it by using he arrow keys opposed to clicking on the calendar?
My ValueChanged changed event
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dateTimePicker1.CustomFormat = "dd/MM/yyyy hh:mm:ss";
if (dateTimePicker1.Checked == true)
{
dateTimePicker1.Enabled = true;
dateTimePicker1.Format = DateTimePickerFormat.Short;
}
else if (dateTimePicker1.Checked == false)
{
dateTimePicker1.Enabled = false;
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";
}
}
I know that DateTimePicker is not easily made nullable and in order so you have to right an extension of the class but this was a quick fix. Any ideas would be much appreciated.
Related
I have a datetimepicker values in datagridview. (Arrival date and departure date)
Here is screen shoot.
Also, I have an edit form for the values in datagrid view.
How can I pass the values of datetimepicker from datagridview to the second form as datetimepicker value.
Here is my try:
private void arrivaldgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
edit edt = new edit();
edt.label12.Text = this.label2.Text;
edt.label13.Text = this.arrivaldgv.CurrentRow.Cells[0].Value.ToString();
edt.textBox1.Text = this.arrivaldgv.CurrentRow.Cells[1].Value.ToString();
edt.textBox2.Text = this.arrivaldgv.CurrentRow.Cells[2].Value.ToString();
edt.textBox3.Text = this.arrivaldgv.CurrentRow.Cells[3].Value.ToString();
/* edt.dateTimePicker1.Value = this.arrivaldgv.CurrentRow.Cells[4].Value; problem here */
edt.ShowDialog();
}
Try the System.Convert.ToDateTime method:
edt.dateTimePicker1.Value = System.Convert.ToDateTime(this.arrivaldgv.CurrentRow.Cells[4].Value);
You can use the DateTime.Parse method:
edt.dateTimePicker1.Value = DateTime.Parse(this.arrivaldgv.CurrentRow.Cells[4].Value);
Most of the .ToX methods use some instance methods internally, such is the case here too, which means that this should work faster than Convert.ToDateTime()
datetimepicker.Value or datetimepicker.Text is always returning the current DateTime, not the selected one. Is there any property that I need to set to get the selected date time.
Below is my code:
private void button1_Click(object sender, EventArgs e)
{
c1.cName = textBox1.Text;
c1.dlv_Time = dateTimePicker1.Value;
string temp = dateTimePicker1.Text;
textBox1.Text = "";
dateTimePicker1.Text = "";
}
In the Form UI, I am changing the time, but in the code Im always receiving the present time.
Thanks in advance
dateTimePicker1.Value.TimeOfDay.ToString()
It will return you the selected time of the date picker control in the string format.
I was editing a different timepicker and reading from a different timepicker.
I have resolved it by changing datetimepicker1 to datetimepicker2.
I'm probably missing something obvious but I can't see it.....
I have a DateTimePicker control (Winforms) to display just the Time HH:mm:ss of the DateTime. The properties are as follows
Checked = False
Format = Time
ShowCheckbox = False
ShowUpDown = True
Value = 28/10/2014 08:00
ApplicationSettings.PropertyBinding.Value = pickTime1
Where pickTime1 is a user setting where Properties.Settings.Default.pickTime1 = 28/10/2014 08:00
I'm expecting the control to display 08:00:00 when the form first loads but it displays the current time. How do I ensure the user setting is displayed when first initialized?
Subscribe to the Form.Load event and set it in there:
private void Form1_Load(object sender, EventArgs e)
{
dateTimePicker1.Value = Properties.Settings.Default.pickTime1;
}
This will display 8:00:00 AM.
If you want 08:00:00, change Format to Custom, and set the CustomFormat property to "hh:mm:ss".
The DateTimePicker.Value must be changed either by code or by user input, otherwise it will set to the current date and time (i.e. DateTime.Now)
I am unable to set the set the Datetimepicker to Null, how can do it. In my project my requirement is to validate the DTPif it is a null, for that I need to set to Null, The code I am using is:
{
dateInsert.Format = DateTimePickerFormat.Custom;
dateInsert.Text = string.Empty;
}
Use the following code:
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";
Take a variable and set its value when DateTimePicker value changes
e.g.
DateTime? myselectedDate = null;
private void DateTimePicker1_ValueChanged(Object sender, EventArgs e) {
myselectedDate = DateTimePicker1.Value;
}
I had a similar question but I could not find an answer I liked. However, I did come up with a suitable solution. Set the "ShowCheckBox" property for the datetimepicker to true. This will put a check box next to the date in the box. Then add the following code.
if (dateTimePicker1.Checked == false)
myVariable = "";
else
myVariable = dateTimePicker1;
Like "karthik reddy" noted above you need to use the 'CustomFormat', however to write back a null to the SQL database (for example) your code has to inspect the DateTimePicker when it 'Adds' or 'Updates' a record, so you need at least two pieces of code. Where a) 'dtp_X' is the DateTimePicker control, b) '_NewRecord' is the custom object that is being sent back to the SQL server, c) 'TheDateProperty' is the particular date field or property of the Custom object
//Call this when the form Loads
private void AllowTheDatePickersToBeSetToNothing()
{
//This let's you set the DatePicker to nothing
dtp_X.CustomFormat = " ";
dtp_X.Format = DateTimePickerFormat.Custom;
}
// Call this when Uploading or Adding the record (_NewRecord) to an SQL database
private void Set_The_Field_Value_based_on_the_CustomFormat_of_the_DateTimePickers()
{
if (dtp_X.CustomFormat == " ")
{
//the date should be null
_NewRecord.TheDateProperty = SqlDateTime.Null;
}
else
{
_NewRecord.TheDateProperty = SqlDateTime.Parse(Convert.ToString(dtp_X.Value));
}
}
//This button resets the Custom Format, so that the user has a way to reset the DateTimePicker Control
private void btn_Reset_dtp_X_Click(object sender, EventArgs e)
{
dtp_X.Format = DateTimePickerFormat.Custom;
dtp_X.CustomFormat = " ";
}
Could anyone please tell me what i should do programmatically to be able to select an item in a listbox using the keyboard when there are multiple items starting with the same character/s.
For eg,
One
Two
Three
Once
Orange
If i want to get the focus on "Once" by typing o,n,c what should i do? Instead of jumping from one item to the other as opposed to the default behaviour.
Add a KeyPress event handler to the ListBox and track the keys that are pressed. Then compare the complete value that already has been typed to the values from the items in the ListBox. If there's a match, select the item.
Edit:
Here's a solution that I created that works. I also measure the time between keypresses. This way, if the time between to keypresses is more than 1.5 seconds, the search-string is emptied and re-filled with the last search-character. After that it's like I said: find a match and if there's a match, select that item. The two private fields are class-level fields to keep track of the time of the last keypress and the string is to store the search-string.
private DateTime _lastKeyPress;
private string _searchString;
private void ListBox1KeyPress(object sender, KeyPressEventArgs e)
{
var newDate = DateTime.Now;
var diff = newDate - _lastKeyPress;
if (diff.TotalSeconds >= 1.5)
_searchString = string.Empty;
_searchString += e.KeyChar;
for (var i = 0; i < listBox1.Items.Count; i++)
{
var item = listBox1.Items[i].ToString();
if (item.ToLower().StartsWith(_searchString))
{
listBox1.SelectedItem = item;
break;
}
}
_lastKeyPress = newDate;
e.Handled = true; //REALLY IMPORTANT TO HAVE THIS
}
And here's an example using LinQ to get a match for the searchitem:
private void ListBox1KeyPress(object sender, KeyPressEventArgs e)
{
var newDate = DateTime.Now;
var diff = newDate - _lastKeyPress;
if (diff.TotalSeconds >= 1.5)
_searchString = string.Empty;
_searchString += e.KeyChar;
var found = listBox1.Items.Cast<object>().Select(t => t.ToString()).Where(item => item.ToLower().StartsWith(_searchString)).FirstOrDefault();
if(!String.IsNullOrEmpty(found))
listBox1.SelectedItem = found;
_lastKeyPress = newDate;
e.Handled = true;
}
Hope this helps! ;)
Edit2:
I don't know if you noticed the comment with the imortance of the e.Handled. By default if you press a key in the ListBox, the control will select the first-found item with that key-character. But it has not the functionality that my code has. So, if you remote the e.Handled line, the code will work but the control will also process the keypress and you don't want that: items will not be correctly selected!
You want to use the LBS_SORT list box style. This style cannot be applied after the control has been created and so to add this style you need to override the CreateParams property. Create a class (lets call it SortedListBox) which derives from ListBox and override this property like so
public class MyListBox : ListBox
{
protected override CreateParams CreateParams
{
get
{
var returnValue = base.CreateParams;
returnValue.Style |= 0x2; // Add LBS_SORT
returnValue.Style ^= 128; // Remove LBS_USETABSTOPS (optional)
return returnValue;
}
}
}
This list box should now both sort the items in your list & support incremental searching (you can't turn the sorting off I'm afraid, if you need to control the sort order then you need to do the incremental searching yourself, as Abbas has suggested)
Update: If you additionally remove the LBS_USETABSTOPS style you even get an edit carret showing what character the incremental search is currently matching on
I just modified Abbas code for my case. This is my desktop program and using in one of the form which has ListBox control. This is working great for me. Thanks to Abbas
private DateTime _lastKeyPress;
private string _searchString;
private void lstEmployer_KeyPress(object sender, KeyPressEventArgs e)
{
var newDate = DateTime.Now;
var diff = newDate - _lastKeyPress;
if (diff.TotalSeconds >= 2)
_searchString = string.Empty;
_searchString += e.KeyChar;
lstEmployer.SelectedIndex = lstEmployer.FindString(_searchString);
_lastKeyPress = newDate;
e.Handled = true; //REALLY IMPORTANT TO HAVE THIS
}