DataRelations.Add

来源:互联网 发布:linux创建新用户和密码 编辑:程序博客网 时间:2024/06/08 08:17

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DataRelation
{
    public partial class frmDataSet : Form
    {
       
        public frmDataSet()
        {
            InitializeComponent();
        }

        private void frmDataSet_Load(object sender, EventArgs e)
        {
            SqlConnection conn=null ;
            string m_sConnStr = "server=(local);Data Source='WWW-F91E7F59A2C';Initial Catalog='SuperMarket';Integrated Security='True'";
            conn = new SqlConnection(m_sConnStr);
            conn.Open();

 

            string mysql = "select*from Type";
            SqlCommand cmd = new SqlCommand(mysql ,conn );
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            cmd.ExecuteNonQuery();


            DataSet ds = new DataSet();
            da.Fill(ds,"Type");

 

            BindingSource parentBindingSourse = new BindingSource();          //parentBindingSourse   type
            parentBindingSourse.DataMember = "Type";
            parentBindingSourse.DataSource = ds.Tables["Type"];


            string mysql2 = "select 编号,名称,产地,进价,类型编号 from product";
            SqlCommand cmd2 = new SqlCommand(mysql2 ,conn);
            cmd2.CommandType = CommandType.Text;
            SqlDataAdapter da2 = new SqlDataAdapter();
            da2.SelectCommand = cmd2;
            cmd2.ExecuteNonQuery();
            da2.Fill(ds, "Product");                


            DataColumn parentColumn = new DataColumn();
            parentColumn = ds.Tables["Type"].Columns ["编号"];

            DataColumn childColumn = new DataColumn();
            childColumn = ds.Tables["Product"].Columns["类型编号"];


           


            ds.Relations.Add("TypeProduct", ds.Tables["Type"].Columns["编号"], ds.Tables["Product"].Columns["类型编号"], false);

            BindingSource childBingSourse = new BindingSource();             //childBingSourse   

 

            childBingSourse.DataMember = "TypeProduct";
            childBingSourse.DataSource = parentBindingSourse;

 

            dgvParent.DataSource = parentBindingSourse;
            dgvChild.DataSource =childBingSourse;

            conn.Close();      
           
                  
        }
      
    }
}

原创粉丝点击