How do I find a particular binding in ControlBindingCollection?

0

I am trying to add an AlreadyBound method to my code so that I can avoid an error

HResult=0x80070057 This causes two bindings in the collection to bind to the same property.

called by

System.Windows.Forms.ControlBindingsCollection.CheckDuplicates(Binding binding)

My code is

        public static void BindText(TextBox box, object dataSource, string dataMember)
    {

        if (AlreadyBound(box,"Text")) return;

        box.DataBindings.Add("Text", dataSource, dataMember, true, DataSourceUpdateMode.OnPropertyChanged);
        if (!(box is SnapTextBox snapbox)) return;
        switch (snapbox.SnapType)
        {
            case SnapBoxType.Money:
                snapbox.DataBindings[0].FormatString = "N2";
                break;
            case SnapBoxType.Real:
                snapbox.DataBindings[0].FormatString = $"N{snapbox.SnapRealDecimals}";
                break;
            case SnapBoxType.Text:
                break;
            case SnapBoxType.Integer:
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }

    private static bool AlreadyBound(TextBox box, string propertyName)
    {
        foreach (var binding in box.DataBindings)
        {
            // what do I put here?  something like
            //if (binding.ToString() == propertyName) return true; 
        }

        return false;
    }

Where SnapTextBox is a user defined control.

How do I get AlreadyBound to work?

c#
data-binding
asked on Stack Overflow Jun 22, 2019 by Kirsten Greed

1 Answer

0

I had trouble figuring out what type binding should be declared as. Finally I tried looking at the type for box.DataBindings[0]

    private static bool AlreadyBound(TextBox box, string propertyName)
    {
        foreach (Binding binding in box.DataBindings)
        {
            if (binding.PropertyName == propertyName) return true; 
        }
        return false;
    }
answered on Stack Overflow Jun 22, 2019 by Kirsten Greed

User contributions licensed under CC BY-SA 3.0