简体   繁体   中英

C#, Empty Datasource, but still an item in the listbox

I have an listbox with a datasource, which is an table from an ADO.net schema. It all works great, but when there is no item in DataSource, there still is a row in the listbox:

System.Collection .Generic.HashSet`1[namespace.class]

How can I prevent this item being added.

 lbAdressen.DataSource = this.adressenSource;
 lbAdressen.DisplayMember = "DisplayName";
 lbAdressen.ValueMember = "Id";

The this.adressenSource var is a BindingSource

You can Add a condition before binding your Source :

if (this.adressenSource != null && this.adressenSource.Count() > 0)
{
 lbAdressen.DataSource = this.adressenSource;
 lbAdressen.DisplayMember = "DisplayName";
 lbAdressen.ValueMember = "Id";
}

That happened to me too.

Within my application I also bound a date to a datetimepicker. But when there is no datasource left in the binding source the datetimepicker would receive the value null. And that is not possible.

To prevent that I added my personal "binder" in between that accepts nullable values and forwards the current date instead.

class MyDateBinder : INotifyPropertyChanged, IBindableComponent
{
    public MyDateBinder()
    {
    }

    private string customFormat;
    public string CustomFormat
    {
        get
        {
            return customFormat;
        }
        set
        {
            if (customFormat != value)
            {
                customFormat = value;
                if (format == DateTimePickerFormat.Custom)
                {
                    UpdateText();
                    FirePropertyChanged("Text");
                }
            }
        }
    }

    private DateTimePickerFormat format = DateTimePickerFormat.Short;
    public DateTimePickerFormat Format
    {
        get
        {
            return format;
        }
        set
        {
            if (format != value)
            {
                format = value;
                UpdateText();
                FirePropertyChanged("Text");
            }
        }
    }

    private string text;
    [Bindable(true)]
    public string Text
    {
        get
        {
            return text;
        }
        set
        {
            if (text != value)
            {
                text = value;
                FirePropertyChanged("Text");
                UpdateDate();
                FirePropertyChanged("Value");
            }
        }
    }

    private DateTime date = DateTime.Now;
    [Bindable(true)]
    public DateTime? Value
    {
        get
        {
            return date;
        }
        set
        {
            if (date != value)
            {
                if (value == null)
                {
                    date = DateTime.Now;
                }
                else
                {
                    date = Convert.ToDateTime(value);
                }
                FirePropertyChanged("Value");
                UpdateText();
                FirePropertyChanged("Text");
            }
        }
    }

    private void UpdateText()
    {
        switch (format)
        {
            case DateTimePickerFormat.Time:
                text = date.TimeOfDay.ToString();
                break;

            default:
            case DateTimePickerFormat.Short:
                text = date.ToShortDateString() + " " + date.ToShortTimeString();
                break;

            case DateTimePickerFormat.Long:
                text = date.ToLongDateString() + " " + date.ToLongTimeString();
                break;

            case DateTimePickerFormat.Custom:
                text = date.ToString(customFormat);
                break;
        }
    }

    private void UpdateDate()
    {
        if(!DateTime.TryParseExact(text, CustomFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
        {
            date = DateTime.Now;
        }
    }

    private BindingContext bindingContext = null;
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
     EditorBrowsable(EditorBrowsableState.Advanced),
     Browsable(false)]
    public BindingContext BindingContext
    {
        get
        {
            if (null == bindingContext)
            {
                bindingContext = new BindingContext();
            }

            return bindingContext;
        }
        set { bindingContext = value; }
    }

    private ControlBindingsCollection databindings;
    [ParenthesizePropertyName(true),
     RefreshProperties(RefreshProperties.All),
     DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
     Category("Data")]
    public ControlBindingsCollection DataBindings
    {
        get
        {
            if (null == databindings)
            {
                databindings = new ControlBindingsCollection(this);
            }
            return databindings;
        }
        set { databindings = value; }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void FirePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event EventHandler Disposed;

    public ISite Site
    {
        get
        {
            return null;
        }
        set
        {
            throw new NotImplementedException();
        }
    }

    public void Dispose()
    {
        if (Disposed != null)
            Disposed(this, new EventArgs());
    }
}

So I could do the databinding:

BindingSource _bs = new BindingSource();
_bs.DataSource = _someDataTables;
_bs.DataMember = _someDataMember;
releaseTimeBinder = new MyDateBinder();
releaseTimeBinder.CustomFormat = "yyyy-MM-dd HH:mm:ss";
releaseTimeBinder.Format = DateTimePickerFormat.Custom;
DateTimePicker dtp_datetime.DataBindings.Add("Value", releaseTimeBinder, "Value");
releaseTimeBinder.DataBindings.Add("Text", _bs, "date_time");

PS: That also gave me the possibility to show the date as date setting of the executing machine.

Hope that helps some lost souls out there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM