The Flower of Evil
asp.net & XML Web Service

导航

 
代码如下:

  1using System;
  2using System.Drawing;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Windows.Forms;
  6using System.Data;
  7using System.Data.SqlClient;
  8
  9namespace DataBinding
 10{
 11    /// 
 12    /// Form1 的摘要说明。
 13    /// 

 14    public class Form1 : System.Windows.Forms.Form
 15    {
 16        private System.Windows.Forms.TextBox textBox1;
 17        private System.Windows.Forms.TextBox textBox2;
 18        /// 
 19        /// 必需的设计器变量。
 20        /// 

 21        private System.ComponentModel.Container components = null;
 22
 23        public Form1()
 24        {
 25            //
 26            // Windows 窗体设计器支持所必需的
 27            //
 28            InitializeComponent();
 29
 30            //
 31            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 32            //
 33        }

 34
 35        /// 
 36        /// 清理所有正在使用的资源。
 37        /// 

 38        protected override void Dispose( bool disposing )
 39        {
 40            if( disposing )
 41            {
 42                if (components != null
 43                {
 44                    components.Dispose();
 45                }

 46            }

 47            base.Dispose( disposing );
 48        }

 49
 50        Windows 窗体设计器生成的代码
 88
 89        /// 
 90        /// 应用程序的主入口点。
 91        /// 

 92        [STAThread]
 93        static void Main() 
 94        {
 95            Application.Run(new Form1());
 96        }

 97
 98        private void Form1_Load(object sender, System.EventArgs e)
 99        {
100            string ConStr=@"Data Source=localhost;Initial Catalog=NorthWind;Integrated Security=SSPI";
101            string SQL="SELECT * FROM Employees";
102            SqlConnection Conn = new SqlConnection(ConStr);
103            SqlDataAdapter da = new SqlDataAdapter(SQL,Conn);
104            DataSet ds = new DataSet();
105
106            //Fill the DataSet with data
107            da.Fill(ds,"Employees");
108
109            //Bind to FirstName column of the Employees table
110            textBox1.DataBindings.Add("Text",ds,"Employees.FirstName");
111
112            //Bind to LastName column of the Employees table
113            textBox2.DataBindings.Add("Text",ds,"Employees.LastName");
114        }

115    }

116}

117

程序运行截图:
 easyADONET.gif

工作原理:
第一次创建应用程序时,Visual Studio .NET 自动生成许多代码, 现在主要探讨Form1_Load方法,
因为那是窗体显示时所调用的方法。

第一项任务是建立与数据源的连接,用结果集填充新创建的DataSet。一旦提取了所有的数据,就用下面
的代码完成世纪绑定:
textBox1.DataBindings.Add("Text",ds,"Employees.FirstName");
textBox2.DataBindings.Add("Text",ds,"Employees.LastName");

使用Add方法将其Text 属性绑定到Employees 表的 FirstName 列。 Add方法采用下面的参数:
* 要绑定到控件属性的名称
*数据源
*字符串文字,数据成员,用来描述绑定值得准确位置
posted on 2005-11-06 19:09  The Flower of Evil  阅读(476)  评论(0)    收藏  举报