how to set datetimepicker with null value if date not selected(c# winforms)

后端 未结 6 1028
夕颜
夕颜 2020-12-14 03:21
Binding b = new Binding( \"Value\", person, \"BdayNullable\", true );
dtBirthdayNullable.DataBindings.Add( b );
b.Format += new ConvertEventHandler( dtBirthdayNullab         


        
6条回答
  •  心在旅途
    2020-12-14 03:44

    this is how i solved it. I couldn't have NULLS so I defined 1/1/1980 12am as MYNULLDATE. I used databinding on the text and value of the datetimepicker. I did not use the checkbox in the datetimepicker. I did not alternat formats from short to custom. It appeared to fire valuechanged events so i just used custom and changed the customformat. I used a flowpanel and a NONBOUND checkbox to sit in front of the datetimepicker.

    Sample of the code

       private void dateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            if (sender != null && sender.GetType() == typeof(DateTimePicker))
            {
                if (((DateTimePicker)(sender)).Value == MYNULLDATE)
                {
                    ((DateTimePicker)(sender)).CustomFormat = " ";
                    checkBoxDate.Checked = false;
                }
                else
                {
                    ((DateTimePicker)(sender)).CustomFormat = "M/d/yyyy";
                    checkBoxDate.Checked = true;
                }
            }
    
        }
    

    In the Non Bound CheckBox

      private void checkBoxDate_Click(object sender, EventArgs e)
        {
            if (bindingSource != null && bindingSource.Current != null &&
                 bindingSource.Current.GetType() == typeof(MyRecord))
            {
                MyRecord a = (MyRecord)bindingSource.Current;
                if (checkBoxDate.Checked == false)
                {
                    a.Date = MYNULLDATE;
                    dateTimePicker.Enabled = false;
                }
                else
                {
                    if (a.Date == null || a.Date == MYNULLDATE)
                    {
                        dateTimePicker.Enabled = true;
                        a.Date = DateTime.Now;
                    }
                }
                bindingSource.ResetBindings(false);
            }
        }
    

提交回复
热议问题