Sikret Miseon
Sikret Miseon

Reputation: 557

vb.net load record data in a text field

im fairly new to databases in vb.net and i have just learned how to use datagridview. im gonna show some of my code for the connection and datagridview display

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

the interface

i want to display in a textfield the first name based on where is the pointer is positioned after i clicked Button1, how do i do this? thank you for the replies!

Upvotes: 0

Views: 2025

Answers (1)

Andrew
Andrew

Reputation: 8674

You need to get that value from the data grid itself, and then show it on the form. There are other ways, but try this (and add null checks!):

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();

Alternately:

If you use a DataSource, and bind the grid to that first, then fill the DataSource with the data, you can use the .Current property to get the selected row.

Edit:

Mistake in code. It should be "DataBoundItem". Not "DataItem". From memory... Also, you need to cast to string, ctype(...,string) or call .ToString().

If you bind to a list of objects, then you won't need to call the .Row, the DataBoundItem will be the actual object type, eg Customer

Upvotes: 1

Related Questions