1

I have a (varchar) field Foo which can only be specified if (bit) Bar is not true. I would like the textbox in which Foo is displayed to be disabled when Bar is true -- essentially, FooBox.Enabled = !isBar. I'm trying to do something like

FooBox.DataBindings.Add(new Binding("Enabled", source, "!isBar"));

but of course the bang in there throws an exception. I've also tried constructs like "isBar != true" or "isBar <> true", but none work. Am I barking up the wrong tree here?

Coderer
  • 25,844
  • 28
  • 99
  • 154
  • +1 because I googled "c# control enabled data binding" and this was the first thing that came up, and is literally the exact situation I'm facing. – vergenzt Jul 23 '12 at 18:08
  • See [binding a usercontrol to the opposite of a bool property](http://stackoverflow.com/a/19718906/298054). – jweyrich Jul 07 '15 at 18:30

3 Answers3

3

As far as I can tell, Databind uses reflection to find the member passed as the 3rd string argument. You cannot pass an expression there, just the member name.

FlySwat
  • 172,459
  • 74
  • 246
  • 311
  • I think Jake has the general idea (making a Property that calculates what you want) but it still feels a bit hacky. – Coderer Dec 05 '08 at 22:27
1

I tried doing something like this a while ago and the best I could come up with was either

a) Changing the source class to also have a NotBar property and bind to that

b) Make a dumb wrapper class around source that has a NotBar property and bind to that.

Jacob Adams
  • 3,944
  • 3
  • 26
  • 42
  • I had an idea sort of like this, but I figured it *should* be possible without resorting to this sort of hack. Apparently not? – Coderer Dec 05 '08 at 22:26
  • I agree that it's a hack. I was quite disappointed by it as well. For my project I basically resorted to making my own system that would handle the the source changing and change the control accordingly. I haven't looked at it much, but WPF databinding is much more advanced, if that's an option. – Jacob Adams Dec 06 '08 at 00:57
  • I'm going to look into WPF when I get a chance. Sadly, the project I'm asking about is just about in the can, so a switch is not an option at this point. But I may transition before my next one... – Coderer Dec 08 '08 at 14:44
  • FYI, I wound up using this as an answer to one of my other questions (about radio buttons). Thanks! – Coderer Dec 17 '08 at 16:29
-1

if isBar is a property of the source class (otherwise you need a property of a class to do the binding) this should work:

FooBox.DataBindings.Add("Enabled", source, "isBar");

but remember that source.isBar must exist and be a boolean.

gcores
  • 12,376
  • 2
  • 49
  • 45
  • 1
    I understand the basic concept, it's just that it seems kind of limited. I was hoping you'd have a little more flexibility. – Coderer Dec 05 '08 at 22:26