十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
1·绑定数据源来进行连接
创新互联建站主营平陆网站建设的网络公司,主营网站建设方案,重庆App定制开发,平陆h5小程序定制开发搭建,平陆网站营销推广欢迎平陆等地区企业咨询
2.用代码连接
先到数据库建立一个数据库和相应的表
连接数据库的代码:
Dim str As String = "Data Source=服务器名;Initial Catalog=数据库名;Persist Security Info=True;User ID=;Password="
dim conn As SqlClient.SqlConnection
try
conn = New SqlClient.SqlConnection
conn.ConnectionString = str
conn.Open()
Return True
Catch ex As Exception
MsgBox(ex.ToString)
Return False
End Try
登录代码:Dim str As String = "Data Source=服务器名;Initial Catalog=数据库名;Persist Security Info=True;User ID=;Password="
dim conn As SqlClient.SqlConnection
conn = New SqlClient.SqlConnection
conn.ConnectionString = str
conn.Open()
sqlstr = "Select * From Amd Where AmdName='" TextBox1.Text "' And AmdPwd = '" TextBox2.Text "'"
Dim sqlcmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(sqlstr, conn)
Dim dr As SqlClient.SqlDataReader
dr = sqlcmd.ExecuteReader
If dr.Read = True Then '判断一条记录为真
kf.Show() '显示下个窗体
Me.Hide() ’隐藏当前窗体
Else
MessageBox.Show("输入信息有误!", "提示")
TextBox1.Text = ""
TextBox2.Text = ""
End If
下面这段代码中,myReader,myCon的关闭应在WHILE循环外。这还不是主要问题,如果你只读取首行首列不要用OleDbDataReader,直接用myCommand.ExecuteScalar就可以了,只要判断一下myCommand.ExecuteScalar返回是否为nothing就行。效率会高很多。
While myReader.Read
If myReader.Item(0) Is System.DBNull.Value Then
Return ""
Else
Return myReader.Item(0)
End If
myReader.Close()
myCon.Close()
End While
使用OleDb将数据库绑定datagridview,然后添加RowHeaderMouseClick事件,在此事件中定义选中某一行后在textbox中显示相应的数据,在添加的按钮中定义打开form2,用sql语句查询数据库得到想要的关键字所关联的数据,显示出来就可以了。这里我给你一部分我写过的代码,基本上和你的要求很像,但是不完全一样,你自己研究研究,改改应该就可以了。
'datagridview绑定数据库
Public Class form1
Private ObjetConnection As OleDbConnection
Private ObjetCommand As OleDbCommand
Private ObjetDataAdapter As OleDbDataAdapter
Private ObjetSet As New DataSet()
' SQL语句
Private strSql As String
Private ObjetDataTable As DataTable
Private ObjetDataRow As DataRow
Private Numeroligne As Integer
'定义路径
Private strConn As String
Private ObjetCommandBuilder As OleDbCommandBuilder
Dim dv As New DataView
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
strConn =
"Provider=Microsoft.ACE.OLEDB.12.0; Data source=" Application.StartupPath "\文件名.accdb" /此处文件路径
strSql =
"Select * 表名 "
ObjetConnection =
New OleDbConnection()
ObjetConnection.ConnectionString = strConn
ObjetConnection.Open()
ObjetCommand =
New OleDbCommand(strSql)
ObjetDataAdapter =
New OleDbDataAdapter(ObjetCommand)
ObjetCommand.Connection() = ObjetConnection
ObjetDataAdapter.Fill(ObjetSet,
"表明")
dv.Table = ObjetSet.Tables(
"表名")
DataGridView1.DataSource = dv
ObjetConnection.Close()
End Sub
/此处是RowHeaderMouseclick事件
Private Sub DataGridView1_RowHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.RowHeaderMouseClick
此处添加显示表中相应信息
Me.TextBox1.text = DataGridView1.SelectedRows(0).Cells(0).Value
Me.TextBox2.text = DataGridView1.SelectedRows(0).Cells(1).Value
.........
End Sub
1.前台配置数据源,那样显示有局限性。
2.用代码绑定数据源,一般都是采用这种方法,其实很简单的。
可以参考小小的世界论坛。