前文介紹了Winform為DataGridView提供的數據自動綁定功能,下面介紹一下采用代碼的數據綁定
1、用DataSet和DataTable為DataGridView提供數據源
先上代碼
private void Form1_Load(object sender, EventArgs e) { String strConn = "Data Source=210.26.*.*;Initial Catalog=Test;User ID=sa;Password=*****"; SqlConnection conn = new SqlConnection(strConn); String sqlId = "select * from [Student] "; conn.Open(); SqlCommand cmd = new SqlCommand(sqlId, conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "student"); //dataGridView1.DataSource=ds.Tables["Student"];此處直接用DataTalbe綁定,與下面兩行代碼的效果是一樣的 dataGridView1.DataSource = ds;//使用Dataset,單必須指定DataMember,因為DataSet是DataTable的集合,而datagridview只能綁定一個datatable dataGridView1.DataMember = "Student"; conn.Close(); }
這里需要指出的是,如果不對dataGridview做任何設置,上面這段代碼將自動將數據綁定到dataGridview上,效果圖如下
這樣的顯示不是很好,那么我只需要將姓名和住址顯示出來怎么辦?那就需要設置datagridview的items屬性或者datagridview右側箭頭——編輯列
除了設置HeaderText顯示列名外,需要設置DataPropertyName屬性必須對應表中的列。
那這樣就可以了嗎?NO,這樣的話,如果繼續運行上面的程序,會出現下圖情況
為什么會這樣尼?明明只是指定了綁定兩個列的,呵呵還需要在代碼里或者屬性里設置一下
dataGridView1.AutoGenerateColumns = false;//此行指定不需要自動綁定數據列,數據列在dataGridView的屬性items集合里指定,必須放在綁定數據之前哦,放到后面是沒用的
對,在代碼里需要加入此行代碼,並且這行代碼必須放在dataGridView.DataSource之前,如果放在后面是沒用的哦。
這塊兒介紹一個列屬性Frozen(凍結)的意思,即如果datagridview有滾動條出現,拉動滾動條時,凍結的列是不會動的,其他的列會跟隨滾動條,上個圖看看,當拉動滾動條時,住址欄已經隱藏起來了,而姓名欄是凍結列true
2、使用IList類集合綁定
我們在軟件開發的過程中,有些數據查出來是IList,再轉DataTable就比較麻煩了,那么能不能直接綁定IList尼?其實也是可以的,貼一點點代碼
IList<Student> lst = StudentService.GetAllOrderbyNumb();//用Student提供的方法查詢到的結果是Ilist dataGridView1.DataSource = lst;
其實就是這么滴簡單。
3、使用SqlDataReader綁定
使用SqlDataReader綁定需要,現在窗體上放置一個數據源控件BindingSource,上代碼
private void Form1_Load(object sender, EventArgs e) { String strConn = "Data Source=210.26.*.*;Initial Catalog=Test;User ID=sa;Password=****"; SqlConnection conn = new SqlConnection(strConn); String sqlId = "select * from [Student] "; conn.Open(); SqlCommand cmd = new SqlCommand(sqlId, conn); SqlDataReader studentlist = cmd.ExecuteReader(); bindingSource1.DataSource = studentlist;//數據源控件bindingSourse是必須的 dataGridView1.DataSource = bindingSource1; conn.Close(); }