代碼講述VB.NET實(shí)現(xiàn)數(shù)據(jù)綁定
VB.NET還是比較常用的,于是我研究了一下VB.NET實(shí)現(xiàn)數(shù)據(jù)綁定,在這里拿出來和大家分享一下,希望對大家有用。以下介紹VB.NET實(shí)現(xiàn)數(shù)據(jù)綁定:
TextBox組件通過下列語句就可以把已經(jīng)得到的數(shù)據(jù)集"myDataSet"中的"books.bookid"字段值綁定到TextBox1的"Text"屬性上:TextBox1.DataBindings.Add ( New Binding ( "Text" , Me.myDataSet , "books.bookid" ) ) 了解了這二點(diǎn),就不難實(shí)現(xiàn)對TextBox組件的數(shù)據(jù)綁定了。下面是VB.NET實(shí)現(xiàn)數(shù)據(jù)綁定的源程序代碼:
- Imports System.Drawing
- Imports System.Windows.Forms
- Imports System.ComponentModel
- Imports System
- Imports System.Data.OleDb
- Imports System.Data
- Public Class Form1
- Inherits Form
- Private WithEvents Button1 As Button
- Private TextBox1 As TextBox
- Private myDataSet As DataSet
- Private components As System.ComponentModel.Container
- Public Sub New ( )
- MyBase.New()
- GetConnected ( )
- InitializeComponent ( )
- End Sub
- '清除在程序中使用過的資源
- Protected Overloads Overrides Sub Dispose ( ByVal disposing As Boolean )
- If disposing Then
- If Not ( components Is Nothing ) Then
- components.Dispose ( )
- End If
- End If
- MyBase.Dispose ( disposing )
- End Sub
- '打開數(shù)據(jù)表,返回?cái)?shù)據(jù)集
- public Sub GetConnected ( )
- '創(chuàng)建一個(gè) OleDbConnection
- Dim strCon As String = " Provider = Microsoft.Jet.OLEDB.4.0; Data Source = ..\sample.mdb"
- Dim myConn As OleDbConnection = new OleDbConnection ( )
- myConn.ConnectionString = strCon
- Dim strCom As string = " SELECT * FROM books "
- '創(chuàng)建一個(gè) DataSet
- myDataSet = new DataSet( )
- myConn.Open ( )
- '用 OleDbDataAdapter 得到一個(gè)數(shù)據(jù)集
- Dim myCommand As OleDbDataAdapter = new OleDbDataAdapter ( strCom , myConn )
- '把Dataset綁定books數(shù)據(jù)表
- myCommand.Fill ( myDataSet , "books" )
- '關(guān)閉此OleDbConnection
- myConn.Close ( )
- End Sub
- '初始化窗體中的組件
- Private Sub InitializeComponent ( )
- Me.Text = "對TextBox組件實(shí)現(xiàn)數(shù)據(jù)綁定!"
- Me.Width = 400
- Me.Height = 300
- Button1 = New Button ( )
- TextBox1 = New TextBox ( )
- Button1.Left = 200
- Button1.Top = 200
- Button1.Width = 100
- Button1.Height = 40
- Button1.TabIndex = 0
- Button1.Text = "數(shù)據(jù)綁定"
- TextBox1.Left = 200
- TextBox1.Top = 30
- TextBox1.Width = 150
- TextBox1.Height = 40
- Me.Controls.Add ( Button1 )
- Me.Controls.Add ( TextBox1 )
- End Sub
- Private Sub Button1_Click ( ByVal sender As Object , _
- ByVal e As System.EventArgs ) Handles Button1.Click
- TextBox1.DataBindings.Add ( New Binding ( "Text" , Me.myDataSet , "books.bookid" ) )
- End Sub
- End Class
- Module Module1
- Sub Main ( )
- Application.Run ( new Form1 ( ) )
- End sub
- End Module
【編輯推薦】