2016-11-20 113 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"; 
     } 
    } 
} 
相關問題