Extract data from Query - sql

Can you please teach me on how to extract data from SQL query access database and place it into a Variable holder? I've been struggling for a week already and i've been really trying hard, please advise Thanks
This is what i have done so far :
Imports System.Data.OleDb
Public Class ModifyForm
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim conn As New OleDbConnection
Private Sub MainMenuButton_Click(sender As Object, e As EventArgs) Handles MainMenuButton.Click
Me.Close()
Form1.Show()
End Sub
Private Sub CloseButton_Click(sender As Object, e As EventArgs) Handles CloseButton.Click
Me.Close()
Form1.Close()
End Sub
Private Sub DeleteBut_Click(sender As Object, e As EventArgs) Handles DeleteBut.Click
End Sub
Private Sub ModifyForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the "Company_dbDataSet1.tbl_empinfo" table. You can move, or remove it, as needed.'
Me.Tbl_empinfoTableAdapter.Fill(Me.Company_dbDataSet1.tbl_empinfo)
End Sub
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
MsgBox(empNum)
Dim conn As New OleDbConnection
conn.Open()
Dim SqlQuerry As String = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
Dim SqlCommand As New OleDbCommand
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
With SqlCommand
.CommandText = SqlQuerry
.Connection = conn
End With
With SqlAdapter
.SelectCommand = SqlCommand
.Fill(Table)
End With
DataGridView1.Rows.Clear()
For i = 0 To Table.Rows.Count - 1
With DataGridView1
.Rows.Add(Table.Rows(i)("EmpID"), (Table.Rows(i)("FirstName")))
End With
Next
'Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"'
conn.Close()
End Sub

Forgetting about the extra code, as was mentioned already, all you need to do is declare your variables:
Dim DBID As Integer ' Or whatever type you're using for the ID field
Dim DBFirstName As String
Then inside the For/Next loop, just use:
DBID = Table.Rows(i)("EmpID")
DBFirstName = Table.Rows(i)("FirstName")
That is only if you're going to use the variables within the for/next loop, otherwise you'll be overwriting them for every record. If you need to store all the values, you'll have to use arrays instead.

Related

Update statement in sql doesnt work , microsoft access with vb.net

I currently doing the changepassword function in my vb.net project, user can click change password to change their password
But my code doesnt update correctly , it will show "updated" but when i go to my database access table the data still remain the same
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.IO
Public Class frmUserDetail
Dim ds As New DataSet
Dim dt As New DataTable
Dim cmd As SqlCommand
Dim con As SqlConnection
Dim da As New OleDbDataAdapter
Dim conn As New OleDbConnection
Private Sub FrmUserDetail_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
loadUserDetail()
txtUserName.Enabled = False ' set it to false so user cannot do shit with it
End Sub
Public Sub loadUserDetail()
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
Dim cmd As OleDbCommand
Dim userName As String = frmMain.lblUserLogin.Text
'specify name of the user
Dim search As String = "SELECT * from tblUser WHERE UserName= '" + userName + "'"
cmd = New OleDbCommand(search)
cmd.Connection = conn
Dim dtt As New DataTable()
Dim daa As New OleDbDataAdapter(cmd)
daa.Fill(dtt)
If dtt.Rows.Count() > 0 Then
txtUserName.Text = dtt.Rows(0)(0).ToString 'show the userName
txtUserPassword.Text = dtt.Rows(0)(1).ToString 'show the password of the user
txtEmail.Text = (dtt.Rows(0)(2).ToString) 'show user email
Else
MsgBox("You are currently login as a guest")
End If
End Sub
Private Sub changePassword()
If cbChangePassword.Checked Then
txtChangePassword.Enabled = True
Else
txtChangePassword.Enabled = Not (True)
End If
End Sub
Private Sub CbChangePassword_CheckedChanged(sender As Object, e As EventArgs) Handles cbChangePassword.CheckedChanged
changePassword()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
conn.Open()
Dim cmd As OleDbCommand
Dim sql As String = "UPDATE tblUser SET UserPassword=#userpass,Email=#email WHERE UserName=#userName;"
cmd = New OleDbCommand(sql.ToString, conn)
cmd.Parameters.AddWithValue("#username", txtUserName.Text)
cmd.Parameters.AddWithValue("#userpass", txtChangePassword.Text)
cmd.Parameters.AddWithValue("#email", txtEmail.Text) 'pass the time variable from the form 1 to the parameter
cmd.ExecuteNonQuery()
MsgBox("updated")
conn.Close()
End Sub
Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Hide()
frmMain.Show()
End Sub
End Class
I Expect my database will get updated when i updated it

Index Out Of Range Exception In VB.NET

When I run the following code, after the ColourAddition(selectedstyle,styleselection.getIndex)="Y" line, I get an error every time and when I run the code without the aforementioned line, the program is a success. Please help me figure it out
Public Class Form1
Dim dbcon As New OleDb.OleDbConnection
Dim DR As OleDb.OleDbDataReader
Dim dr1 As OleDb.OleDbDataReader
Dim com As New OleDb.OleDbCommand
Dim com1 As New OleDb.OleDbCommand
Dim ChkdItm As Integer
Dim NoOfStyles As Integer
Dim NoOfColours As Integer
Dim SelectedStyle As Integer
Dim temp As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbcon.ConnectionString = "Provider= Microsoft.Ace.OLEDB.12.0; Data Source= CheckedListBox.accdb"
dbcon.Open()
com.CommandText = "Select * from ColourTable"
com1.CommandText = "Select * from StyleTable"
com1.Connection = dbcon
com.Connection = dbcon
DR = com.ExecuteReader
dr1 = com1.ExecuteReader
While dr1.Read
NoOfStyles += 1
End While
While DR.Read
ColoursClb.Items.Add(DR.GetString(1))
NoOfColours += 1
End While
SelectedStyle = StyleSelection.getIndex
End Sub
Public colourAddition(NoOfStyles, NoOfColours) As String
Private Sub AddColourBtn_Click(sender As Object, e As EventArgs) Handles AddColourBtn.Click
If ColoursClb.CheckedItems.Count > 0 Then
For Each ChkdItm In ColoursClb.CheckedIndices
colourAddition(SelectedStyle, StyleSelection.getIndex) = "Y"
Next
End If
End Sub
Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
StyleSelection.Show()
End Sub
End Class
The error is showing on the line where "Next" is written

VB.Net, Problem updating table from DataGridView

This is my first post so forgive me if I goof!
I am trying to update myself from VBA to VB.Net. Using loads of help from Google etc I am doing Ok except when I try to update my table from a DataGridView. It just does not update. What I would like is that a cell is update on change. My code so far is shown (I have tried all sorts of builder, tables etc so my code may have a smattering of these that are redundant):
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.SqlServer
Public Class FrmData
Private dsS As DataSet = New DataSet
Private adpS As SqlDataAdapter
Private builder As SqlCommandBuilder
Private bsource = New BindingSource
Private Sub FrmData_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
Dim sqlS = "SELECT [Data].[Date] AS [Date] ,
[Data].[PaidBy] AS [Paid By] ,
[Data].[PaidAmount] AS [Paid Amount (£)],
[Data].[AmountLeft] AS [Amount Left (£)]
FROM [Data] WHERE [Data].[Name]= '" & strName & "'
ORDER BY [Data].[Date] DESC"
Dim adpS As SqlDataAdapter
adpS = New SqlDataAdapter(sqlS, connection)
builder = New SqlCommandBuilder(adpS)
Dim dTable As New DataTable
bsource.DataSource = dTable
bsource.EndEdit()
adpS.Fill(dTable)
connection.Close()
DataGridView1.DataSource = dTable
End Sub
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
DataGridView1.EndEdit()
Dim dt As DataTable
dt = TryCast(DataGridView1.DataSource, DataTable)
Dim x As Integer = 0
If dt.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
Dim builder = New SqlCommandBuilder(adpS)
Dim rowsAffected As Integer = adpS.Update(dt)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
End If
End Sub
End Class
Any help would be appreciated.
This is for SQL Server, right. Try it like this.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class
After two days working on this, I finally got it right for myself! Also, I had an eye on #ryguy72 codes as well. these are the steps you can take to get there:
Step 1: Drag and drop DataGridView into your form
Step 2: In the App.config add this between configuration:
<connectionStrings>
<add name="ehsanConnection" connectionString="Data Source=XXX
; User= XX; Password= XXX" ProviderName="System.Data.SqlClient"/>
</connectionStrings>
Step 3: The code below shows how you can get the DataGridView programmatically right, it worked perfectly fine for me.
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Dim connStr As String =
ConfigurationManager.ConnectionStrings("ehsanConnection").ToString
Dim connStri = New SqlConnection(connStr)
Dim sql As String = "SELECT * FROM [Ehsan].[dbo].[Data]"
sCommand = New SqlCommand(sql, connStri)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Data")
sTable = sDs.Tables("Data")
connStri.Close()
DataGridView1.DataSource = sDs.Tables("Data")
The main point here was that I had to use [Ehsan].[dbo].[Data] not only the name of the table, "Data". Actually, it didn't work for me that way and it kept complaining!
Step 4: If you want to update your database after you changed some of the records in datagridview, use this code :
sAdapter.Update(sDs.Tables(0))
Main important point is that: "you have to set a primary key in your table first otherwise it won't work!"

Displaying Data from SQL in TextBox by clicking ComboBox item in Visual Basic 2012

I have three columns in SQL, which I want the data displayed in three textboxes by clicking an item in ComboBox.
The issue is not really displaying. I can save the data fine and display. However, one of the text fields will only show one cell and not update when a different item is selected. Hope this is making sense.
Here is the code I have for saving:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO MyDiary (Title, DiaryContent, DiaryDate) VALUES (#Title, #DiaryContent, #DiaryDate)"
myconnect.Open()
Try
mycommand.Parameters.Add("#Title", SqlDbType.VarChar).Value = TextBox1.Text
mycommand.Parameters.Add("#DiaryContent", SqlDbType.VarChar).Value = TextBox2.Text
mycommand.Parameters.Add("#DiaryDate", SqlDbType.VarChar).Value = TextBox3.Text
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
And here is the code for displaying in form1:
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim ds As New DataSet
Dim da As New SqlDataAdapter
Dim sql As String
Dim inc As Integer
Dim MaxRows As Integer
Dim max As String
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'RioDiaryDataSet5.MyDiary' table. You can move, or remove it, as needed.
Me.MyDiaryTableAdapter.Fill(Me.RioDiaryDataSet5.MyDiary)
Dim con As New SqlConnection(" Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True")
Dim cmd As New SqlCommand("Select Title,DiaryContent,DiaryDate FROM MyDiary ")
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
cmd.Connection = con
da.Fill(ds, "MyDiary")
con.Open()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.DisplayMember = "Title'"
ComboBox1.ValueMember = "DiaryContent"
End Sub
Private Sub NewEntryToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewEntryToolStripMenuItem.Click
AddEntry.Show()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If (Not Me.ComboBox1.SelectedValue Is Nothing) Then
Me.TextBox2.Text = ComboBox1.Text
Me.TextBox3.Text = ComboBox1.SelectedValue.ToString
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("DiaryDate").ToString() 'Where ColumnName is the Field from the DB that you want to display
End If
End Sub
End Class
As you can see from the code, I want to display Title and DiaryContent in two separate textboxes by clicking on Title in the Combobox. This works fine.
The issue I have is DiaryDate only shows the first entry and does not update when selecting the Item from ComboBox.
Can anyone help?
You can try to play with ComboBox's SelectedItem property. Since ComboBox's DataSource is DataTable here, SelectedItem of ComboBox represent a row in DataTable. Given DataRow in hand, you can display value of any column of DataRow in TextBoxes :
........
If (Not Me.ComboBox1.SelectedItem Is Nothing) Then
Dim SelectedItem = TryCast(comboBox1.SelectedItem, DataRowView)
Me.TextBox1.Text = SelectedItem.Row("Title").ToString()
Me.TextBox2.Text = SelectedItem.Row("DiaryContent").ToString()
Me.TextBox3.Text = SelectedItem.Row("DiaryDate").ToString()
End If
........
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from Register"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
Dim id = reader.Item("cid")
ComboBox1.Items.Add(id)
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from register where cid ='" + ComboBox1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
TextBox1.Text = reader.Item("cname")
TextBox2.Text = reader.Item("dob")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Why is my DataGridView in VB.Net doubling in size every time I access the Access Database?

I have some basic code here that calls in an Access Database ("Houses") and that's about all. However, every time I click the button, the size of the DataGridView doubles. What I mean is that if the actual Access database has 5 rows, the DataGridView shows the correct database initially, but after each click of the button it goes up to 10 rows (they repeat), then 15, then 20 etc. Unfortunately I can't place this in the Form_Load area.
I tried placing "dt.rows.clear()" before "dgv.DataSource = dt", but it wipes everything. Also tried "DirectCast(Dgv.DataSource, DataTable).Rows.Clear()" and "Dgv.Datasource = Nothing"
Public Class frmHouses
Dim dt As DataTable = New DataTable()
Dim connStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Houses.accdb"
Dim sqlStr As String = "SELECT * FROM Property"
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim dataAdapter As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sqlStr, connStr)
dataAdapter.Fill(dt)
dataAdapter.Dispose()
dgv.DataSource = dt
End Sub
Thanks!
Public Class frmHouses
Dim connStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Houses.accdb"
Dim sqlStr As String = "SELECT * FROM Property"
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim dt As DataTable = New DataTable()
Dim dataAdapter As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sqlStr, connStr)
dataAdapter.Fill(dt)
dataAdapter.Dispose()
dgv.DataSource = dt
End Sub
OR you can
Public Class frmHouses
Dim dt As DataTable = New DataTable()
Dim connStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Houses.accdb"
Dim sqlStr As String = "SELECT * FROM Property"
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
dt.clear()
Dim dataAdapter As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sqlStr, connStr)
dataAdapter.Fill(dt)
dataAdapter.Dispose()
dgv.DataSource = dt
End Sub
Public Class frmHouses
Dim dt As DataTable = New DataTable()
Dim connStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Houses.accdb"
Dim sqlStr As String = "SELECT * FROM Property"
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim dataAdapter As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sqlStr, connStr)
dataAdapter.Fill(dt)
dataAdapter.Dispose()
IF dgv.Rows.Count > 0 Then
dgv.Rows.Clear()
End IF
dgv.DataSource = dt
End Sub