VB.Net连接.mdf数据库的实例
分类:VB.Net
乐博网lob.cn提示:调试环境为 vs2005 + windows2003 / windows2008 / xp / vista + .NET Framework 2.0
代码如下:
Option Strict On Imports System.IO Imports System.Data.SqlClient
Public Class LOB
Private Sub LOB_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim dbFileNames As String() = Directory.GetFiles(Environment.CurrentDirectory + "\乐博网", "*.mdf") For Each dbFileName As String In dbFileNames Me.cboLocalDatabase.Items.Add(dbFileName) Next '把指定目录下的.mdf数据库文件罗列出来
End Sub
Private Sub cboLocalDatabase_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboLocalDatabase.SelectedIndexChanged ' 利用 SqlConnectionStringBuilder 对象来构建连接字符串。 Dim connectStringBuilder As New SqlConnectionStringBuilder() connectStringBuilder.DataSource = "(local)\SQLEXPRESS" ' 将 SQL Server 数据库文件的完整绝对路径指派给 AttachDBFilename 属性。 connectStringBuilder.AttachDBFilename = Me.cboLocalDatabase.SelectedItem.ToString connectStringBuilder.IntegratedSecurity = True ' 只连结数据库而不附加数据库。 connectStringBuilder.UserInstance = True
Try Using cn As New SqlConnection(connectStringBuilder.ConnectionString) cn.Open()
Dim myCMD As New SqlCommand("SELECT * FROM sys.tables", cn)
Using myReader As SqlDataReader = myCMD.ExecuteReader()
' 将 BindingSource 组件系结至 SqlDataReader。 Me.BindingSource1.DataSource = myReader
' 将 DataGridView 控件系结至 BindingSource 组件。 Me.DataGridView1.DataSource = Me.BindingSource1
End Using '更多.net源码和教程,来自[乐博网 www.lob.cn] End Using
Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub End Class
|