2016-11-20 80 views
0

如何将2个SQL Server表中的数据加载到1个datagridview中?像我有2个表:C#如何从多表中加载数据到DataGridView [SQL Server]

Jobs:Job_ID, Client_ID 

EmployeeJobs:Emp_ID, Job_ID, Hours_Spent, Job_Date 

我希望他们能够出现在一个datagridview的,什么是正确的方法是什么?

+2

可能重复[DataGridView绑定到两个表](http://stackoverflow.com/questions/10302272/datagridview-binding-to-two-tables) – timothyclifford

回答

0

SQL JOIN表,将结果绑定到网格。

0

绑定的DataGridView以下SQL选择:

SELECT Jobs.Job_ID, Jobs.Client_ID, EmployeeJobs.Emp_ID, EmployeeJobs.Job_ID, EmployeeJobs.Hours_Spent, EmployeeJobs.Jobs_Date 
FROM Jobs 
INNER JOIN EmployeeJobs 
ON Jobs.Job_ID=EmployeeJobs.Job_ID; 
0

这将做你想做的。

using System; 
using System.Data; 
using System.Data.SqlClient; 
using System.Windows.Forms; 

namespace WindowsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     string connetionString; 
     SqlConnection connection; 
     SqlDataAdapter adapter; 
     SqlCommandBuilder cmdBuilder; 
     DataSet ds = new DataSet(); 
     DataSet changes; 
     string Sql; 
     Int32 i; 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"; 
      connection = new SqlConnection(connetionString); 
      Sql = "select * from Product"; 
      try 
      { 
       connection.Open(); 
       adapter = new SqlDataAdapter(Sql, connection); 
       adapter.Fill(ds); 
       connection.Close(); 
       dataGridView1.DataSource = ds.Tables[0]; 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show (ex.ToString()); 
      } 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       cmdBuilder = new SqlCommandBuilder(adapter); 
       changes = ds.GetChanges(); 
       if (changes != null) 
       { 
        adapter.Update(changes); 
       } 
       MessageBox.Show("Changes Done"); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.ToString()); 
      } 
     } 
    } 
} 

这是另一种方法。

using System; 
using System.Data; 
using System.Windows.Forms; 
using System.Data.SqlClient; 

namespace WindowsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"; 
      string sql = "SELECT * FROM Authors"; 
      SqlConnection connection = new SqlConnection(connectionString); 
      SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection); 
      DataSet ds = new DataSet(); 
      connection.Open(); 
      dataadapter.Fill(ds, "Authors_table"); 
      connection.Close(); 
      dataGridView1.DataSource = ds; 
      dataGridView1.DataMember = "Authors_table"; 
     } 
    } 
} 
相关问题