【问题标题】:How do I change DataBinding index position programmatically如何以编程方式更改 DataBinding 索引位置
【发布时间】:2015-10-08 09:43:20
【问题描述】:

如何以编程方式更改 DataBinding 索引位置?

例如:我有一个名为 MYLIST<T>list<> 集合,并且在表单 TEXTBOX1LISTBOX1 上放置了两个控件,这两个控件都是绑定MYLIST<T>

在执行时,从 MYLIST 填充 LISTBOX 控件,当我单击 LISTBOX1-Item 时,TEXTBOX1.Text 根据 MYLIST 的选定索引更改,因为这两个控件都与 MY LIST 绑定。

我想以编程方式设置列表索引位置 2。就像我单击一个按钮时一样,因此 TEXTBOX1.Text 应根据列表索引 [2] 更改,单击 LISTBOX1 的第二项时的行为相同。

我试过 .Select 但没有运气,

这里是示例代码:

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

【问题讨论】:

    标签: c# winforms data-binding generic-list


    【解决方案1】:

    你可以使用这样的东西

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

    阅读以下 MSDN 链接BindingContext Class
    Control.BindingContext Property

    ,您可能会发现有用

    【讨论】:

    • @HaseebAhmed 找到答案后,您可以点击答案附近的复选标记以接受它。您只能检查一个答案是否被接受,而您可以通过单击答案附近的向上箭头来投票给您认为有帮助的尽可能多的答案。这样,将来对其他用户会更有帮助。您也可以为好的问题投票。
    猜你喜欢
    • 2010-12-04
    • 2019-07-16
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 2011-06-23
    相关资源
    最近更新 更多