I am currently trying to implement a relatively simple data management app.
I have a class Member
and a BindingList<Member> membersList
, as well as a ListBox
and some TextBox
es.
The ListBox
is bound to membersList
.
Now I, ideally, want to bind the TextBox
es to ListBox.SelectedItem
, so that whatever element the user has selected in the ListBox
, when they edit a TextBox
the element in membersList
is updated.
I tried just binding the TextBox
es to ListBox.SelectedItem
, but this made the Binding
to the actual element that ListBox.SelectedItem
is referencing at the moment of the binding creation, not whichever item is selected in the ListBox
.
firstNameTextBox.DataBindings.Add(new Binding("Text",
membersList.SelectedItem, "firstName", false,
DataSourceUpdateMode.OnPropertyChanged));
I actually solved this already by just clearing and recreating the Bindings
for the TextBox
es in the membersList_SelectedIndexChanged(object sender, EventArgs e)
event handler, but this feels very "hacky" and I suspect there is a more standard solution.
Another idea I had was to just make the Binding
s to a Member temporaryMember
that is set to ListBox.SelectedItem
inside the membersList_SelectedIndexChanged(object sender, EventArgs e)
event handler, but then I have to manually write the changes through to the corresponding item in membersList
which also makes me feel like this isn't the optimal solution.
Is there a way to make the Binding
dynamic, in the sense that, upon creation, I indicate to it that the DataSource is changing?
Or a standard way the change the Binding
s DataSource without deleting it and creating a new one? (Or is this actually best practice?)
(Another thing to mention: I am new to Bindings
in C# and while searching for solutions, I found out that there apparently are two different classes, one in the System.Windows.Data
namespace and another in the System.Windows.Forms
namespace. I think I am using the class from the latter. Maybe I should use the other one?)