vb.net load record data in a text field - vb.net

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
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!

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

Related

I am new to VB (Visual Studio) and I am trying to get the column (2) "LastName" from the Datatable "ClientInfo" in Ascending Order

Below is what I have written and am having trouble figuring out how to send it in Ascending order to the database (in Access) and to retrieve it in Ascending order as well.
I will try to show you my code so that it will be easier to help me.
Is anyone able to help me on this.
Public Class Form1
Dim inc As Integer
Dim MaxRows As Integer
Dim IdNum As Integer
Dim con As New OleDb.OleDbConnection 'THE CONNECTION OBJECT
Dim dbProvider As String 'HOLDS THE PROVIDER
Dim dbSource As String 'HOLDS THE DATA SOURCE
Dim MyDocumentsFolder As String 'HOLDS THE DOCUMENTS FOLDER
Dim TheDatabase As String 'HOLDS THE DATABASE NAME
Dim FullDatabasePath As String 'HOLDS THE DATABASE PATH
Dim ds As New DataSet 'HOLDS A DATASET OBJECT
Dim da As OleDb.OleDbDataAdapter 'HOLDS A DATA_ADAPTER OBJECT
Dim sql As String 'HOLDS AN SQL STRING
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'SET UP THE PROVIDER
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
'SET THE DATABASE AND WHERE THE DATABASE IS
TheDatabase = "/ClientInfo.mdb"
MyDocumentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
FullDatabasePath = MyDocumentsFolder & TheDatabase
'SET THE DATA SOURCE
dbSource = "Data Source = " & FullDatabasePath
'SET THE CONNECTION STRING
con.ConnectionString = dbProvider & dbSource
'OPEN THE DATABASE
con.Open()
'STORE THE SQL STRING
sql = "SELECT * FROM tblContacts"
'PASS THE SQL STRING AND CONNECTION OBJECT TO THE DATA_ADAPTER
da = New OleDb.OleDbDataAdapter(sql, con)
'FILL THE DATASET WITH RECORDS FROM THE DATABASE TABLE
da.Fill(ds, "ClientInfo")
'CLOSE THE DATABASE
con.Close()
'GET HOW MANY ROWS ARE IN THE DATABASE TABLE
MaxRows = ds.Tables("ClientInfo").Rows.Count
'SET A VALUE FOR THE INC VARIABLE
inc = -1
'SET A VALUE FOR THE ID NUM VARIABLE
IdNum = inc + 1001
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("ClientInfo").NewRow()
dsNewRow.Item("FirstName") = txtFirstName.Text
dsNewRow.Item("LastName") = txtLastName.Text
dsNewRow.Item("CompanyName") = txtBusName.Text
dsNewRow.Item("Address") = txtAddress.Text
dsNewRow.Item("City") = txtCity.Text
dsNewRow.Item("State") = txtState.Text
dsNewRow.Item("Zip") = txtZip.Text
dsNewRow.Item("HomePh") = txtHomePh.Text
dsNewRow.Item("Mobile") = txtMobile.Text
dsNewRow.Item("BusinessPh") = txtBusPh.Text
dsNewRow.Item("Ext") = txtExt.Text
dsNewRow.Item("Email") = txtEmail.Text
ds.Tables("ClientInfo").Rows.Add(dsNewRow)
da.Update(ds, "ClientInfo")
MessageBox.Show("New Record added to the Database")
Clear()
End Sub
End Class
The Order By clause will sort the records returned by the column indicated. The default is ascending but you can add DESC or Descending depending on the database if you want the order reversed.
sql = "SELECT * FROM tblContacts Order By LastName;"
I'm not sure if your problem is with the query or I don't get you, but if you want to fill the data adapter with the LastName column just use this as a sql query:
SELECT LastName FROM tblContacts ORDER BY LastName ASC

Filling Datagrid from separate form without removing data

I select a value in the combo-box in the form Addsubject().
This takes all the values from my database with the same value and adds them to the DGV.
Only issue is when i try to add a second value from the combo-box it replaces the first.
Form addsubject() has a button that when clicked takes the data and places it in the form1 dgv.
Private Sub btnAddSub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddSub.Click
Dim comboboxvalue As String
comboboxvalue = "'" & CBClass.SelectedItem & "'"
Dim sql As String
sql = "Select * From class Where ClassCode=" & comboboxvalue
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\ProjectDatabase.mdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter(sql, MyConn)
da.Fill(ds, "Class")
Dim view As New DataView(tables(0))
source1.DataSource = view
Form1.dgv.DataSource = view
End Sub
Images of the issue
Pre-button click
Post-Click
New value and button click

Adding more rows to a datagridview in vb.net

Private Sub btnAddSub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddSub.Click
Dim comboboxvalue As String
comboboxvalue = "'" & CBClass.SelectedItem & "'"
Dim sql As String
sql = "Select * From class Where ClassCode=" & comboboxvalue
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=H:\ProjectDatabase.mdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter(sql, MyConn)
da.Fill(ds, "Class")
Dim view As New DataView(tables(0))
source1.DataSource = view
Form1.dgv.DataSource = view
End Sub
I can currently add one piece of data to the datagrid. When I try to add a second piece of data it replaces the current data stored.
How do I make it so that when I add more data it goes to a new line.
The source code you provided looks a lot like you are just refreshing the data source for the DGV on every btnAddSub click, by assigning to form1.dgv.datasource each time. If you want to simply append new rows to the DGV you will need to manipulate the DGV.Rows collection by adding DataGridViewRow objects to it.

Filtering SQL data by ListBox item to display in DataGridViews

I can't get the listbox item to filter properly.
Basically, I want to click an item in my ListBox and that will populate the DataGridView accordingly. I have 2 DataGridViews which will display different criteria based on the ListBox item selected.
My code so far is the following:
Public Class Form1
Dim str As String = "Data Source=XXXXX;Initial Catalog=XXXXXX;Integrated Security=True"
Dim con As New SqlConnection(Str)
Dim com As String = "Select swname, numoflic from SW2"
Dim com2 As String = "Select name, instdate, swinsta, organ from Assigned2"
Dim Adpt As New SqlDataAdapter(com, con)
Dim Adpt2 As New SqlDataAdapter(com2, con)
Dim ds, ds2 As New DataSet()
Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim dt As DataTable
dt = New DataTable("SW2")
'DEFINING LISTBOX ITEM AS STRING
Dim curItem As String = ListBox1.SelectedItem.ToString()
ds.Tables.Clear()
ds2.Tables.Clear()
Adpt.Fill(ds, "ContactPerson2")
DataGridView1.DataSource = ds.Tables(0)
Adpt2.Fill(ds2, "Assigned2")
DataGridView2.DataSource = ds2.Tables(0)
End Sub
You'll need to filter your data set as explained here. Also, I'd recommend you don't refill your datatables in the event handler. Load them both in Form_Load and then just pass Nothing to the filter to clear any prior filters in the beginning of the SelectedIndexChanged event handler.
I changed the code around a bit and what works for me now is the code below.
Dim curItem As String = ListBox1.SelectedItem(1)
Dim sqlConnectionString As String = "Data Source=XXXX;Initial Catalog=XXXXX;Integrated Security=True"
Dim sqlSelect As String = "Select swname, number from SW"
Dim da As New SqlDataAdapter(sqlSelect, sqlConnectionString)
Dim dt As New DataTable
da.Fill(dt)
'filter setting defined here
Dim filter As String = "swname = '" + curItem + "'"
'filter rows
Dim FilteredRows As DataRow() = dt.Select(filter)
For Each row As DataRow In FilteredRows
DataGridView1.DataSource = FilteredRows.CopyToDataTable()
Next

Visual Basic 2008 New Search Query

I'm trying to do a search through an access database I added to a project but I get this error: An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll"
Additional information: No value given for one or more required parameters.
The idea was to search the database for text entered into a textbox, then display the information on that row within more text boxes.
The code dr = cmd.ExecuteReader is also highlighted as an issue when debugging. I'm using visual basic 2008, and quite new to the whole coding scene so explanations as to why the issue has occurred would be appreciated!
Imports System.Windows.Forms
Imports System.Data.OleDb
Public Class frmSearch
Public con As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Dim dbProvider As String
Dim dbSource As String
Dim BillingSystemFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Private Sub frmSearch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'BillingdatabaseDataSet.BillingInfo' table. You can move, or remove it, as needed.
Me.BillingInfoTableAdapter.Fill(Me.BillingdatabaseDataSet.BillingInfo)
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
'Setup the provider
TheDatabase = "/billingdatabase.accdb"
BillingSystemFolder = Application.StartupPath
FullDatabasePath = BillingSystemFolder & TheDatabase
'Set the database and the location of it
dbSource = "Data Source = " & FullDatabasePath
'Set the data source
con.ConnectionString = dbProvider & dbSource
'Set the connection string
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
txtJobNum.Clear()
txtName.Clear()
txtSurname.Clear()
Dim str As String
str = "SELECT * FROM BillingInfo WHERE (Code = " & CodeText.Text & ")"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
dr = cmd.ExecuteReader
While dr.Read()
txtSurname.Text = dr("Surname").ToString
txtName.Text = dr("First Name").ToString
txtJobID.Text = dr("Customer ID").ToString
End While
con.Close()
End Sub
End Class
Probably the field Code is a text field. In this case when you want to search using a particular value for that field you should enclose the value between single quotes.
Something like this
str = "SELECT * FROM BillingInfo WHERE (Code = '" & CodeText.Text & "')"
However this is really a bad practice because this allows to create an Sql Injection attack or it will simply fail because your value contains a single quote.
The correct method is using a parameterized query like this
str = "SELECT * FROM BillingInfo WHERE (Code = #p1)"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = CodeText.Text
dr = cmd.ExecuteReader