C#学习笔记(8)

今天我们来说一下C#中的数据绑定机制

 BindingSource组件是.Net在Windows Forms数据绑定方面最重要的创举之一,它能够为窗体封装数据源,让控件的数据绑定操作更加简便。使用时,一般先在窗体上加入一个BindingSource组件,接着将BindingSource组件绑定至数据源,最后再将窗体上的控件绑定至BindingSource组件。通常将BindingNavigator控件与BindingSource组件搭配使用,以便浏览BindingSource组件的数据源。

我们通过一个窗口程序来了解一下数据绑定功能。

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public int Myvalue { get; set; }
        
        public Form1()
        {
            InitializeComponent();
            Myvalue = 1;
            textBox2.DataBindings.Add("Text", this, "Myvalue");
            
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Myvalue =int.Parse ( textBox1.Text);
            textBox2.DataBindings.Clear();
            textBox2.DataBindings.Add("Text", this, "Myvalue");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Myvalue = 0;
            textBox2.DataBindings.Clear();
            textBox2.DataBindings.Add("Text", this, "Myvalue");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Myvalue ++;
            textBox2.DataBindings.Clear();
            textBox2.DataBindings.Add("Text", this, "Myvalue");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Myvalue--;
            textBox2.DataBindings.Clear();
            textBox2.DataBindings.Add("Text", this, "Myvalue");
        }
    }
}

为了简便的说明原理,我只绑定类内的一个属性

我们进行数据绑定的时候运用DataBindings.Add方法,这个方法一般有三个必备的参量,需要绑定的属性(一般为文本框的文本), 数值源的来源,要绑定的列或属性

我们这里面要绑定Form1 的一个实例中的属性,因此使用this,这里面还要注意,一个文本框的文本只能绑定一个数据源,如果需要更改数据源,我们需要先清除原有的数据源,在这个程序中,还有一个问题我目前没有解决,那就是没有办法进行动态的更改被绑定的属性,这一点需要继续去研究。

 

posted on 2015-05-06 20:27  ljc825  阅读(170)  评论(0编辑  收藏  举报

导航