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 ComplexBinding
 10{
 11    /// 
 12    /// Form1 的摘要说明。
 13    /// 

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

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

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

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

 45            }

 46            base.Dispose( disposing );
 47        }

 48
 49        Windows 窗体设计器生成的代码
 82
 83        /// 
 84        /// 应用程序的主入口点。
 85        /// 

 86        [STAThread]
 87        static void Main() 
 88        {
 89            Application.Run(new Form1());
 90        }

 91
 92        private void Form1_Load(object sender, System.EventArgs e)
 93        {
 94            string ConStr=@"Data Source=localhost; Initial Catalog=Northwind;Integrated Security=SSPI";
 95            //SQL Query
 96            string SQL ="SELECT * FROM Customers";
 97            SqlConnection Conn = new SqlConnection(ConStr);
 98            SqlDataAdapter da = new SqlDataAdapter(SQL,Conn);
 99            DataSet ds = new DataSet();
100            da.Fill(ds,"Customers");
101            //Bind the whole table to the DataGrid control
102            dataGrid1.SetDataBinding(ds,"Customers");
103        }

104    }

105}

106

   程序运行截图:
ComplexBinding.gif

工作原理:

vs 自动生成代码不谈, 说Form1_Load方法。
一旦建立了与数据源的连接,就是用DataAdapter 用 Customers表填充DataSet.
dataGrid1.SetDataBinding(ds,"Customers");
在我们的例子中,使用DataSet作为数据源,使用包含在DataSet内的Customers表作为数据成员。
如果打算把控件的DataSource属性绑定到Customers表,则可以在代码中使用这个方法。另外
你还可以使用下面这行代码替换SetDataBinding方法:
dataGrid1.DataBinding.Add("DataSource",ds,"Customers");
需要为控件的其他属性添加多个绑定时,这种方法特别有用。

posted on 2005-11-06 20:40  The Flower of Evil  阅读(609)  评论(0)    收藏  举报