可以将控件数据中的更改反映回其数据源吗? [英] Can change in a control's data be reflected back to its datasource?

查看:69
本文介绍了可以将控件数据中的更改反映回其数据源吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#编程新手,目前正在使用Windows Forms。只是想获得一些关于'DataBinding'的知识,但直到现在都没有成功。我对Internet进行了广泛的研究,但无法理解DataBinding的用途以及它是如何工作的。我所知道的是,我们设置任何控件的DataSource并将其绑定到该源,然后该源中的更改将在该控件中更新,反之亦然。对吗?



现在我尝试做的是我做了以下表格:

listBox1,listBox2, textBox,button



我想在listBox1中添加项目。随着项目在listBox1中添加,它们会在listBox2中自动更新,如果从listBox2中删除任何项目,则从listBox1中删除相同内容。

我使用TextBox和Button将项目添加到listBox1。我编写了以下不成功的代码来将项目添加到listBox1并在listBox1更新时更新listBox2:



I am new to C# programming and currently working on Windows Forms. Just want to gain some knowledge on 'DataBinding' but unsuccessful till now. I did an extensive research on Internet but couldn't understand what DataBinding is meant for and how does it work. What I have come to know is that we set the DataSource of any control and bind it to that source then the change in that source will be updated in that control and vice-versa. Right?

Now what I tried to do is I made the following form:
listBox1, listBox2, textBox, button

I want to add items in listBox1. As the items are added in listBox1 they get automatically updated in listBox2 and if any item is deleted from listBox2, the same gets deleted from listBox1.
I used a TextBox and a Button to add items to listBox1. I wrote the following unsuccessful code to add the items to listBox1 and to update listBox2 whenever listBox1 gets updated:

public partial class Form1 : Form
    {
        BindingSource bs=new BindingSource();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add(textBoxItem.Text);
            bs.DataSource = listBox1.Items;
            listBox2.DataSource = bs;
        }
    }





当我在listBox1中插入第一个项目时,我也在listBox2中获取该项目但是之后没有项目在listBox2中添加,而项目很容易添加到listBox2。

如何实现此任务,如果可能请提供编码,以便删除listBox2中的任何项目时,它会得到也从listBox1中删除。我将按一个按钮从listBox2中删除项目。

谢谢!



When I insert the first item in listBox1, I get that item in listBox2 as well but no item gets added in listBox2 after that while the items are easily added to listBox2.
How can I achieve this task and if possible please provide the coding for when any item from listBox2 is deleted, it gets deleted from listBox1 as well. I will put a button to delete item from listBox2.
Thank you!

推荐答案

你可以使用..bs.ResetBindings(false)刷新绑定源的数据。
You can use..bs.ResetBindings(false) to refresh the data of the binding source.


这篇关于可以将控件数据中的更改反映回其数据源吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆