找到你要的答案

Q:How do I change DataBinding index possition programmatically

Q:我如何更改绑定指数位置编程

How do I change DataBinding index possition programmatically?

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

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"));


    }


}

please advice,

thanks

我如何更改绑定指数位置编程?

例如:我有一个列表<;>;收集命名mylist和两个控件放置在窗体和控件的实例数目都与mylist。

在execusion时间,得到填充ListBox控件从mylist当我点击数目项实例。改变文字的每mylist选定的指标都是控制我的列表的绑定。

我想设置列表的索引位置2编程。当我点击一个按钮的实例。文本应按列表索引[ 2 ]的变化,同样的行为时,点击第二项数目。

我试过了,但没有运气,

这里是示例代码:

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"));


    }


}

请建议,

谢谢

answer1: 回答1:

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 andControl.BindingContext Property

你可以使用这样的东西

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

你可能会发现有用的阅读下面的链接andcontrol.bindingcontext MSDN BindingContext类属性

c#  winforms  data-binding  generic-list