开发者

Winforms, databinding, Listbox and textbox

开发者 https://www.devze.com 2023-01-01 10:59 出处:网络
I have a ListBox (MyListBox) on my screen, and a Textbox (MyTextBox). The ListBox is filled with a List(Of T), which are all custom items.

I have a ListBox (MyListBox) on my screen, and a Textbox (MyTextBox).

The ListBox is filled with a List(Of T), which are all custom items.

Now I try to do this:

The ListBox' datasource is the List(Of T).

Now when an Item changes I want the textbox to be updated to a particular property of the selected item in my ListBox.

In code this means:

Me.MyListBox.DisplayMember = "SelectionName"
Me.MyListBox.ValueMember = "Id"

MyTextbox.DataBindings.Add(New Binding("Text", Me._listOfItems, "SelectedItem.Comment", True, DataSourceUpdateMode.OnPropertyChanged))

Me.MyListBox.DataSource = Me._listOfItems

this does not work. But when I bind to SelectedValue i开发者_开发问答nstead of SelectedItem it works perfectly.

The _listOfItems is declared as this:

Dim _listOfItems As List(Of MyItem) = New List(Of MyItem)()

Where MyItem is this:

public class MyItem
{
    public string SelectionName { get; set; }
    public int Id { get; set; }
    public string Comment { get; set; }
}

I tried overriding the ToString() in MyItem so that it would use that. But that doesn't work either.

Anybody care to give it a try?


One of the easiest way, I guess, would be to use a BindingSource, setting it as the ListBox.DataSource property to your BindingSource on design.

  1. Drop a BindingSource on your form;
  2. Set your ListBox.DataSource property to your BindingSource;
  3. Set your ValueMember and DisplayMember properties just like you're actually doing;
  4. Make your DataBinding for your TextBox control, and use your BindingSource as the source, using your MyItem.Comment property;
  5. Assign your List(Of MyItem) to your Binding.DataSource property;
  6. Your TextBox should follow the CurrencyManager.CurrentItem's Comment property, that is, the currently ListBox.SelectedItem.

Indeed, you would perhaps need to implement the INotifyPropertyChanged interface to make it work properly.

But if this all work perfect with the SelectValue, why don't you just use it?


The code below shows how I am doing it. I first set my ListBox DataSource to a class with a collection of BindingList. The class implements IBindingList. I have two TextBoxes I want to bind the SelectedItem to. The code below is how I am doing it:

lbControl.DataSource = SharepointTestBusinessLayer.Control.ListAll();
lbControl.DisplayMember = "ControlName";
lbControl.SelectedIndex = 0;
scTextBoxControlID.DataBindings.Add("Text", this.lbControl.DataSource, "ControlID");
scTextBoxControlName.DataBindings.Add("Text", this.lbControl.DataSource, "ControlName");
0

精彩评论

暂无评论...
验证码 换一张
取 消