Visual Basic 2005——如何绑定到一个IEnumerable数据来源
以下的程序代码示范如何将DataGridView控件绑定到一个SqlDataReader对象:
Private Sub CH3_DemoForm034_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
' 利用SqlConnectionStringBuilder对象来构建连接字符串。
Dim connectStringBuilder As New SqlConnectionStringBuilder()
connectStringBuilder.DataSource = "(local)\SQLEXPRESS"
connectStringBuilder.InitialCatalog = "北风贸易"
connectStringBuilder.IntegratedSecurity = True
Try
Using cn As _
New SqlConnection(connectStringBuilder.ConnectionString)
' 开启连接。
cn.Open()
Dim foxCMD As New SqlCommand( _
"SELECT 身份证字号,姓名,员工性别,自传 " & _
"FROM 飞狐工作室WHERE 自传IS NOT NULL", cn)
Using drFox As SqlDataReader = foxCMD.ExecuteReader()
' 将BindingSource组件绑定到SqlDataReader。
Me.BindingSource1.DataSource = drFox
' 将DataGridView控件绑定到BindingSource组件。
Me.DataGridView1.DataSource = Me.BindingSource1
End Using
End Using
Catch err As SqlException
MessageBox.Show(err.Message, "SQL Exception", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
End Sub