Reputation: 45
I have a Winforms application in which there is a listbox and a textbox. The listbox displays a list of items via a BindingList, and for each item the property Name of the item is shown. I want to display the Fullname of the item in the TextBox alongside the list for the selected item in the list.
Creating the BindingList for the ListBox was no problem, but I could not get the TextBox to work. I found a question on SO (Binding a TextBox to a ListBox SelectedItem) which gave an example, but I still can't get it to work. The code compiles perfectly, but the TextBox shows nothing.
Here is the code I've written:
itemList = new BindingList<Item>();
itemSource = new BindingSource(itemList, null);
lstItems.DataSource = itemSource; // previously I used itemList which also seemed to work?
txtItem.DataBindings.Add(new Binding("Text", itemSource, "Fullname", false, DataSourceUpdateMode.OnPropertyChanged));
Fullname is a property of the Item class, and I've tried all sorts of combinations of BindingList/BindingSource in the above example, but nothing seems to work.
I must be missing something, but I fail to see what. Could anyone point me in the right direction? Thanks!
EDIT: added the item class for Pavan Chandaka
public class Item
{
private string fullname;
public Item(string fullname)
{
this.fullname = fullname;
}
public string Fullname()
{
return "Fullname: " + fullname;
}
public override String ToString()
{
return Fullname();
}
}
Upvotes: 1
Views: 103
Reputation: 12751
Your Item
class do not have a property for appropriate binding.
Keep it simple and try below modified Item
class.
public class Item
{
//PROPERTY
public string Fullname { get; set; }
//CONSTRUCOR
public Item(string fullname)
{
this.Fullname = fullname;
}
//OVERRIDE TOSTRING
public override string ToString() => $"{this.Fullname}";
}
Upvotes: 1