zoukankan      html  css  js  c++  java
  • What is the proper way to bind Nullable DateTime property to DateTimePicker?

    I have an object that I'm trying to bind its properties to two DateTimePicker controls.

    class Order
    {
    public DateTime OrderPlacedDate { get; }
    public Nullable<DateTime> ShippedDate { get; }
    }
    

    What is the proper way to bind Nullable DateTime Property to DateTimePicker?

    There's not really a right way since the DateTimePicker does not have good support for null values. You have a couple of options:

    1. You can use a ReadOnly TextBox and a MonthCalendar rather than a DateTimePicker. You'd bind to the TextBox and use the MonthCalendar to set the date in the TextBox.

    2. You can use DateTimePicker's null support which is a little clumsy from a UI perspective. This also requires you to write some glue code that maps the DateTimePicker's null representation to a null on your Nullable<DateTime> property. You can do this as follows:

    Customer _customer; // Has a Nullable<DateTime> property called "HireDate"
    private void Form1_Load(object sender, EventArgs e)
    {
    // Create Customer
    _customer = new Customer("555", "John Doe", 1000, DateTime.Now);
    // Bind
    Binding binding = new Binding("Value", _customer, "HireDate", true);
    this.dateTimePicker1.DataBindings.Add(binding);
    // BindingComplete
    binding.Format += new ConvertEventHandler(Binding_Format);
    binding.Parse += new ConvertEventHandler(Binding_Parse);
    }
    void Binding_Parse(object sender, ConvertEventArgs e)
    {
    // Need to make the Control show NULL
    Binding binding = sender as Binding;
    if (null != binding)
    {
    DateTimePicker dtp = (binding.Control as DateTimePicker);
    if ((null != dtp) && (dtp.Checked))
    e.Value = new Nullable<DateTime>();
    }
    }
    void Binding_Format(object sender, ConvertEventArgs e)
    {
    INullableValue inv = (e.Value as INullableValue);
    if ((null != inv) && (!inv.HasValue))
    {
    // Need to make the Control show NULL
    Binding binding = sender as Binding;
    if (null != binding)
    {
    DateTimePicker dtp = (binding.Control as DateTimePicker);
    if (null != dtp)
    {
    dtp.ShowCheckBox = true;
    dtp.Checked = false;
    e.Value = dtp.Value;
    }
    }
    }
    }
    
    ---------------------------------------------------------------------
    每个人都是一座山.世上最难攀越的山,其实是自己.往上走,即便一小步,也有新高度
    .

    --做最好的自己,我能!!!

  • 相关阅读:
    成功并不是要得到什么,而是要放弃什么
    Qt一步一步实现插件通信(附源码)
    Qt一步一步实现插件调用(附源码)
    推荐大家阅读——《你的知识需要管理》
    移动商机十人谈__移动红利
    如果再不要求进步,那么你就是下一个陨落的巨头
    贫穷的本质__如何改变穷人的现状?
    贫穷的本质__缺乏对未来的信心和长远规划
    痛苦并愉快的被洗着_品牌洗脑
    Qt_Pro详解
  • 原文地址:https://www.cnblogs.com/tonyepaper/p/1203659.html
Copyright © 2011-2022 走看看