1
votes

How do I change DataBinding index position programmatically?

For Example: I have a list<> collection named MYLIST<T> and two controls placed on form TEXTBOX1 and LISTBOX1 both controls are bind with MYLIST<T>.

at the time of execusion, LISTBOX control get filled from MYLIST and when I am clicking on LISTBOX1-Item, TEXTBOX1.Text changing as per selected index of MYLIST as both are controls are bind with MY LIST.

I want to set list index position 2 programmatically. like when I click on a button so TEXTBOX1.Text should change as per list index[2], the same behaviour when clicking second item of LISTBOX1.

I have tried .Select but no luck,

here is sample code:

public partial class Form1 : Form
{
    public sealed class Person
    {
        public string name { get; set; }
    }
    private List<Person> myList = new List<Person>();
    public Form1()
    {
        InitializeComponent();

        myList.Add(new Person(){name = "MyName1"});
        myList.Add(new Person(){name = "MyName2"});
        myList.Add(new Person(){name = "MyName3"});

        textBox1.DataBindings.Add(new Binding("Text", myList, "name"));

        listBox1.DataSource = myList;
        listBox1.DisplayMember = "name";
        listBox1.ValueMember= "name";
    }

    private void button2_Click(object sender, EventArgs e)
    {
        myList.Select(person => person.name.StartsWith("MyName2"));
    }
}
1

1 Answers

2
votes

You can use something like this

BindingContext[myList].Position = myList.FindIndex(person => person.name.StartsWith("MyName2"));

You may find useful reading the following MSDN links BindingContext Class and
Control.BindingContext Property