2013-03-02 65 views
0

數據我如何檢索在組合框中選擇的數據,並從數據庫中檢索數據的信息datagridview的檢索,在組合框中選擇datagridview的

+0

這是在WinForms的吧?似乎是一個相當基本的問題btw,你谷歌嗎? – bas 2013-03-02 22:26:16

+0

是的,它winforms – user2119170 2013-03-02 22:27:45

+0

和我goolge它,但我找不到答案 – user2119170 2013-03-02 22:28:30

回答

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

namespace WindowsFormsApplication12 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 
     SqlConnection cn = new SqlConnection("data source=localhost;initial catalog=acc;uid=sa;pwd=emotions"); 
     private void Form1_Load(object sender, EventArgs e) 
     { 
      SqlDataAdapter da = new SqlDataAdapter("select ClassId, Class from Class order by ClassId", cn); 
      DataTable dt = new DataTable();    
      da.Fill(dt); 
      comboBox1.DataSource = dt; 
      comboBox1.DisplayMember = "Class"; 
      comboBox1.ValueMember = "ClassId"; 
     } 
     private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e) 
     { 
      SqlDataAdapter da = new SqlDataAdapter("select SNAme, FName, SPhoneNo from Students where ClassId =" + comboBox1.SelectedValue, cn); 
      DataTable dt = new DataTable(); 
      da.Fill(dt); 
      dataGridView1.DataSource = dt; 
     } 
    } 
} 

enter image description here