Pass DataTable from Class to Main Form - vb.net

I am stupidly new to VB.. I have my Class (dalv1) where all my functions are stored and my Main Form.
Code is as follows:
Public Sub getCustomerDetails()
Try
Dim cust_dataTable As New DataTable()
Dim Connection As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source = C:\Users\Public\Documents\VP - A1\Database\Database.mdb"
Dim SQL As String = ("SELECT * FROM tblCustomers")
Dim dataAdapter As New OleDbDataAdapter(SQL, Connection)
dataAdapter.Fill(cust_dataTable)
dataAdapter.Dispose()
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
I want to pass the DataTable, cust_dataTable to the Main Form so I can populate text boxes when the form loads.

You need to turn it into a function so that the table gets returned to the caller:
Public Function getCustomerDetails() As DataTable
Dim cust_dataTable As New DataTable()
Try
Dim Connection As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source = C:\Users\Public\Documents\VP - A1\Database\Database.mdb"
Dim SQL As String = ("SELECT * FROM tblCustomers")
Dim dataAdapter As New OleDbDataAdapter(SQL, Connection)
dataAdapter.Fill(cust_dataTable)
dataAdapter.Dispose()
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
Return cust_dataTable
End Function
You didn't share your form's code, but here is an example of how you would call it:
Private da As New dalv1
Private _MyDataTable As DataTable
Protected Overrides Sub OnLoad(ByVal e As EventArgs)
MyBase.OnLoad(e)
_MyDataTable = da.getCustomerDetails
End Sub

Related

how to send a multiple message using datagridview in selecting a checkbox in vb.net?

Here is my code:
'for clicking the datagridview
Private Sub DataGridView1_CellContentClick_1(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Try
MySqlConnection.ConnectionString = "Server=localhost; User=root;Password='';Database=lrbhams;"
MySqlConnection.Open()
Dim state3 As String = "select boarder_fname, boarder_contact, guardian, guardian_number from boarders_info"
Dim command As New MySqlCommand(state3, MySqlConnection)
'command.Connection.Open()
command.ExecuteNonQuery()
MySqlConnection.Close()
If DataGridView1.Rows(e.RowIndex).Cells(2).Value Then
TextBox1.Text = DataGridView1.Rows(e.RowIndex).Cells(2).Value
ElseIf DataGridView1.Rows(e.RowIndex).Cells(4).Value Then
TextBox1.Text = DataGridView1.Rows(e.RowIndex).Cells(4).Value
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
''
End Sub
For sending message:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim message As String
'Dim reader As MySqlDataReader
message = RichTextBox1.Text
If send_sms.SerialPort.PortName = send_sms.portName Then
send_sms.SerialPort.Write("AT" & vbCrLf)
send_sms.SerialPort.Write("AT+CMGF=1" & vbCrLf)
send_sms.SerialPort.Write("AT+CMGS=" & Chr(34) & TextBox1.Text & Chr(34) & vbCrLf)
send_sms.SerialPort.Write(message & Chr(26))
MsgBox("Text Message Successfully Send !!!")
Try
Dim connectString As String
Dim conn As New MySqlConnection
Dim reader As MySqlDataReader
Dim command As MySqlCommand
'Dim mysqlQuery As String
connectString = "server=localhost;user=root;database=lrbhams"
conn = New MySqlConnection(connectString)
Dim query As String
conn.Open()
query = "INSERT into admin_log_attendance (action,contact_number, date) VALUES ('" & RichTextBox1.Text & "','" & TextBox1.Text & "', '" & Date.Today & "')"
command = New MySqlCommand(query, conn)
reader = Command.ExecuteReader
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
MySqlConnection is a class in the MySql.Data.MySqlClient namespace. It is not a static class so it must be instantiated with the New keyword. You cannot set properties or call methods on the class itself. You must created an instance of the class. It is best practice to use `Using...End Using blocks for database objects. It will ensure that the database objects are closed and disposed even if there is an error.
A Select statement is not a NonQuery. Insert, Update and Delete statements can be run with command.ExecuteNonQuery but not Select. A Select query can be run with .ExecuteScalar if a single piece of data is expected or .ExecuteReader if several columns and/or rows are expected.
You can't just execute a Select command and expect something to happen. I suspect you want to display the data in your grid so let's fill a DataTable (an in memory representation of the records returned) with the .Load method then bind it to the DataGridView.
No need to close the connection because the Using block will close it.
If you call .ToString on a class that doesn't override the method you will just get the fully qualified name of the class. The Exception class provides a Property called Message which you can use.
The filling of the DataGridView will go in a separate method which you can call from Form.Load.
Now that there is data in the DataGridView you can click on it and the CellContentClick event will fire. I hope Cell(2) and Cell(4) Booleans because that is the only why your If statement will work. The necessity of the conversion code and .ToString will be obvious once you turn on Option Strict. (See my comment)
That's enough for now. With all this and Option Strict you should be able to fix the second part of your code.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RetrieveRecordsForDataGridView()
End Sub
Private Sub RetrieveRecordsForDataGridView()
Dim dt As New DataTable
Try
Using cn As New MySqlConnection("Server=localhost; User=root;Password='';Database=lrbhams;")
Dim state3 As String = "select boarder_fname, boarder_contact, guardian, guardian_number from boarders_info"
Using command As New MySqlCommand(state3, cn)
cn.Open()
dt.Load(command.ExecuteReader())
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If CBool(DataGridView1.Rows(e.RowIndex).Cells(2).Value) Then
TextBox1.Text = DataGridView1.Rows(e.RowIndex).Cells(2).Value.ToString
ElseIf CBool(DataGridView1.Rows(e.RowIndex).Cells(4).Value) Then
TextBox1.Text = DataGridView1.Rows(e.RowIndex).Cells(4).Value.ToString
End If
End Sub

How to feed results of SQL statement into a GridView, not the SQL statement itself?

This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is. Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox. Here is my code.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
sqlConn.Open()
Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
Dim dsColumns As New DataSet
Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)
daAdapter.Fill(dsColumns)
If dsColumns.Tables(0).Rows.Count > 0 Then
ListBox1.Items.Clear()
For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim SqlStr As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim myItem As String
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
connection = New SqlConnection(connetionString)
'Dim iIndex As Integer = ListBox1.SelectedIndex
myItem = ListBox1.SelectedItem
SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
adapter = New SqlDataAdapter(SqlStr, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I guess the problem is passing the SQL to the GridView. When I select the first Item, I see this in my GridView.
SELECT [OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry]
FROM [Test].[dbo].[Orders]
That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.
This is what I see now.
I want to see something more like this.
Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns. Now, if I stretch out the form window, the GridView stays static.
You need to actually run the retrieved Sql statement:
sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
Dim cmd As New SqlCommand(sqlstr, connection)
Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
cmd.Dispose()
adapter = New SqlDataAdapter(sqlstr_report, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Use the .Anchor property of the DataGridView to make it resize with the form

How to select an excel data Table using a drop downlist value

I am working on an application that uses excel files as its data source. I would love the DataGridView to populate with the columns of a sheet when a worksheet name is selected from the drop down list.
Here is what I have tried doing:
Imports System.Data.OleDb
Public Class Form101
Public cn As New OleDbConnection
Public cm As New OleDbCommand
Public da As OleDbDataAdapter
Dim comb As String
Public dt As New DataTable
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Comb1.SelectedIndexChanged
comb = Comb1.SelectedText
End Sub
Public Sub FillDataGridView(ByVal Query As String)
da = New OleDbDataAdapter(Query, cn)
dt.Clear()
da.Fill(dt)
With DataGridView1
.DataSource = dt
.Columns(0).HeaderText = "Date"
.Columns(1).HeaderText = "Qty brought"
.Columns(2).HeaderText = "Qty sold"
.Columns(3).HeaderText = "Goods balance"
.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
cn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\toojah app\Stock card.xls; Extended Properties= Excel 8.0;"
cn.Open()
FillDataGridView("select * FROM ['" & comb & "'] ")
End Sub
End Class
Try something like this. The first function will collect all of the columns and records in your excel file and place it into a datatable. Then If you wanted to add additional columns to the datable you can do it in the Public Sub CreateDataGridView. This has been tested and works.
Friend Shared Function BuildDatatable () as datatable
Dim dt As New DataTable
Dim Conn As System.Data.OleDb.OleDbConnection
Dim cmd As System.Data.OleDb.OleDbDataAdapter
dim MyFile as string = "C:\toojah app\Stock card.xls"
Conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + MyFile + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';")
Conn.Open()
Dim dtSheets As DataTable = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [" & drSheet("TABLE_NAME").ToString() & "]", Conn)
cmd.TableMappings.Add("Table", "Net-informations.com")
cmd.Fill(dt)
Conn.Close()
Next
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function
'This is used to pass the function datatable as a dt to then pass to the public sub as shown below.
Dim dt As DataTable = BuildDatatable
Public Sub CreateDataGridView(dt)
Dim newColumn As New Data.DataColumn("ComeColumnName", GetType(System.String))
newColumn.DefaultValue = "YourValues"
dt.Columns.Add(newColumn)
DataGridView1.DataSource = dt
End Sub

Edit selected row in DataGridView in new form

I have a management system which has a form with DataGridView showing records.
I want to be able to click on a row and click on a 'edit' button, new 'edit form' should come up with all of the record details.
The datagrid grid only shows a few of the fields from ms access around 7/21 fields using of course select statement.
How do I show all of the fields and its details in a new form when I click edit?
This is my DBControl class:
Imports System.Data.OleDb
Public Class DBControl
'create db connection
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=IPM_DB.accdb;")
'prepare db command
'variable for database commands
Private DBcmd As OleDbCommand
'db data
'a place to store our data
'storing and handling
'public because will be accessed from main form
'data adapter can perform select, insert, update and elete SQL operations in data source
'executing commands against database, perform actions ie filling data table
Public DBDA As OleDbDataAdapter
'data table
Public DBDT As DataTable
'query parameters
Public Params As New List(Of OleDbParameter)
'query statistics
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
'reset query statistics
RecordCount = 0
Exception = ""
Try
'open a connection
DBCon.Open()
'create db command
DBcmd = New OleDbCommand(Query, DBCon)
'load paramsinto db command
Params.ForEach(Sub(p) DBcmd.Parameters.Add(p))
'clear params list
Params.Clear()
'execute command and fill datatable
DBDT = New DataTable
DBDA = New OleDbDataAdapter(DBcmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
'close connection
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
'include query & command parameters
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
my current edit form:
Public Class Edit_Incident_Record
Privte Access As New DBControl
Private CurrentRecord As Integer = 0 'Incident.dgvData.SelectedRows(0).Index
Private Sub Edit_Incident_Record_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim currID As Integer = Incident.dgvData.SelectedRows(0).Cells("IncidentID").Value.ToString()
Access.ExecQuery("SELECT * from Incidents where IncidentID = '" & currID & "'")
Dim r As DataRow = Access.DBDT.Rows(currID)
'Access.ExecQuery("SELECT * from Incidents where IncidentID = '" & currID & "'")
txtIncidentID.Text = currID
'txtSummary.Text = r("Summary").ToString
End Sub
End Class
and finally my edit button
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
If Me.dgvData.SelectedRows.Count = 0 Or Me.dgvData.SelectedRows.Count > 1 Then
MessageBox.Show("Select just one row")
Return
End If
Edit_Incident_Record.Show()
End Sub
Thank You all!

how to use recordset movelast

i need help for the code that i can use old rs.movelast to vb.net 2010..
any simple way to query my record that automatic select the last..
here is my connection sample i just call it only in any form..///
Public Function ExecuteSQLQuery(ByVal SQLQuery As String) As DataTable
Try
Dim sqlCon As New OleDbConnection(CnString)
Dim sqlDA As New OleDbDataAdapter(SQLQuery, sqlCon)
Dim sqlCB As New OleDbCommandBuilder(sqlDA)
sqlDT.Reset() ' refresh
sqlDA.Fill(sqlDT)
Catch ex As Exception
MsgBox("Error : " & ex.Message)
End Try
Return sqlDT
End Function
sqlDT.rows(sqlDT.rows.count-1) will be the last record of your DataTable sqlDT. sqlDT.rows.count-1 will return you the last index of the rows in the filled table. Hope it will help you. Thanks
Imports System.Data.OleDb
Public Class Form1
Public CnString As String = "Provider=SQLOLEDB;Data Source=HP-PC\SQLEXPRESS;Persist Security Info=True;Password=sa;User ID=sa;Initial Catalog=Accounts"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ssql As String = "Select * from TBL_Access"
Dim dt As DataTable
dt = ExecuteSQLQuery(ssql)
TextBox1.Text = dt.Rows(dt.Rows.Count - 1)(0) 'Value of First Column of Last Row of DataTable dt
TextBox2.Text = dt.Rows(dt.Rows.Count - 1)(1) 'Value of Second Column of Last Row of DataTable dt
End Sub
Public Function ExecuteSQLQuery(ByVal SQLQuery As String) As DataTable
Try
Dim sqlCon As New OleDbConnection(CnString)
Dim sqlDA As New OleDbDataAdapter(SQLQuery, sqlCon)
Dim sqlCB As New OleDbCommandBuilder(sqlDA)
Dim sqlDT As New DataTable
sqlDT.Reset() ' refresh
sqlDA.Fill(sqlDT)
Return sqlDT
Catch ex As Exception
MsgBox("Error : " & ex.Message)
Return Nothing
End Try
End Function
End Class