我对vb.net中的数据库相当新,我刚学会了如何使用datagridview。我将展示我的一些连接和datagridview显示的代码
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet 'holds table data
Dim da As OleDb.OleDbDataAdapter 'connection to database connectionobject
Dim sql As String
Dim inc As Integer
Dim MaxRows As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:/AddressBook.mdb"
con.ConnectionString = dbProvider & dbSource
'alternative way of connection
'Dim fldr As String
'Environment is the user profile
'fldr = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "/AddressBook.mdb"
'dbSource = "Data Source = " & fldr
con.Open()
MsgBox("Database is now Open")
sql = "select * from tblContacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Addressbook")
con.Close()
MsgBox("Database is now Closed")
MaxRows = ds.Tables("AddressBook").Rows.Count
inc = -1
MsgBox(MaxRows)
TextBox1.Text = inc
DataGridView1.DataSource = ds
DataGridView1.DataMember = "AddressBook"
End Sub
End Class
我想在文本字段中显示第一个名称,根据我点击Button1后指针所在的位置,我该怎么做?谢谢你的回复!
答案 0 :(得分:1)
您需要从数据网格本身获取该值,然后在表单上显示它。还有其他方法,但尝试这个(并添加空检查!):
Dim row as DataRow = CType(DataGridView1.CurrentRow.DataBoundItem, DataRowView).Row
myTextBox.Text = row["firstName"].ToString();
C#
var row = ((DataRowView)dataGridView1.CurrentRow.DataBoundItem).Row;
myTextBox.Text = row["firstName"].ToString();
可替换地:
如果您使用DataSource,并将网格首先绑定到该网格,然后使用数据填充DataSource,则可以使用.Current
属性来获取所选行。
修改强>
代码中的错误。它应该是“DataBoundItem”。不是“DataItem”。从内存...此外,您需要转换为字符串,ctype(...,string)
或致电.ToString()
。
如果绑定到对象列表,则不需要调用.Row
,DataBoundItem将是实际的对象类型,例如Customer