Ishamael
Ishamael

Reputation: 1

C#(Winforms) Databinding using Listbox.SelectedValue as data source (master-detail)

I have a listbox bound to a List<object> as its DataSource. What I'm wanting to do is use the SelectedValue property of the Listbox (i.e the object corresponding to the current selection) as a DataSource for some textboxes that will display certain values of the object for editing. I've tried

TextBox.DataBindings.Add(new Binding("Text", ListBox, "SelectedValue.name"));    

and

TextBox.DataBindings.Add(new Binding("Text", ListBox.SelectedValue, "name"));

but as there is nothing selected in the ListBox (because the form hasn't been shown yet), I get an exception about "Value cannot be null".

Now I know that I can (re)bind to ListBox.SelectedValue in my form's SelectionChangeCommitted handler (that is, after a selection has been made), but if i have to do that I might as well just set the TextBox's value directly (admittedly I could just do this to resolve the issue, but I'd like to learn more about databinding).

So my question is, in short: Is it possible to bind to ListBox.SelectedValue once (initially, before the ListBox has a selection) and avoid the null value exception, and if so, how?

Upvotes: 0

Views: 2226

Answers (2)

Jay Riggs
Jay Riggs

Reputation: 53593

I'm not sure which control your projectNameCtrl is, but you'll want to bind your TextBox. Something like this:

textBox1.DataBindings.Add(new Binding("Text", listBox1, "selectedvalue"));

Where:
textBox1 is your TextBox
listBox1 is your ListView

EDIT
You should be able to data bind a ListBox even if that ListBox has no selected items so your 'value cannot be null' must be for another reason. I suggest using the debugger to determine which object specifically is null.

You can ensure you don't data bind a control more than once by first checking the control's DataBindings.Count property; if it's equal to zero you haven't yet data bound that control:

if (textBox1.DataBindings.Count == 0) {
    // OK to data bind textBox1.
}

Upvotes: 1

Quanta
Quanta

Reputation: 465

Off the top of my head, I think you'd need to do something on each selectedItemChanged event...

I know this doesn't answer your question, but I'd look at using WPF instead since this is so much more elegant to do in WPF, and let's face it, by not creating a GUI in code (using XAML instead) your sanity will be much more intact when you finish your project. I don't recall enough windows forms, but in WPF, you just implement INotifyPropertyChanged on your back-end object that you're binding to, and then when you bind to the SelectedItem property of that ListBox, you automatically get updates since the SelectedItem property is a DependencyProperty.

Upvotes: 0

Related Questions