Accessing data from ms access and displaying in grid view - vb.net

I am not able to display any data in grid view,Its a blank datagrid
The connection is open and everything is fine but data is not getting displayed!! I am a newbie
Imports System.Data.OleDb
Class Form2
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Open()
Dim dvginfo As DataGridView
Dim table As New DataTable("Address")
Dim da As New OleDbDataAdapter("Select * FROM Address", con)
Dim dtrow As DataTable
da.Fill(table)
If table.Rows.Count = 0 Then
Return
End If
For Each dtrow In table.Rows
dvginfo.Rows.Add()
dvginfo.Rows(dvginfo.RowCount - 1).Cells("colFirstname").Value = dtrow("Firstname").ToString()
dvginfo.Rows(dvginfo.RowCount - 1).Cells("colLastname").Value = dtrow("Lastname").ToString()
dvginfo.Rows(dvginfo.RowCount - 1).Cells("colDOB").Value = Convert.ToDateTime(dtrow("DOB").ToString())
Next
dvginfo.ClearSelection()
con.Close()
End Sub
End Class

Try this...
Imports System.Data.OleDb
Class Form2
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Open()
Dim dvginfo As DataGridView
Dim table As New DataTable("Address")
Dim da As New OleDbDataAdapter("Select * FROM Address", con)
Dim dtrow As DataTable
da.Fill(table)
dvginfo.DataSource = table
con.Close()
End Sub
End Class

Related

SQL Column to TextBox (from ComboBox)

I have managed to add data into a ComboBox from a column out of my SQL table, but I need the rows from across to display in the rest of the textboxes. (I hope I have worded this correctly).
Here is my code currently:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
The above works with no issues, all of the items add into the ComboBox but I need the corresponding rows from the other two columns which are EMAIL_ADDRESS and DEPARTMENT to add into TextBoxes from what is selected in the ComboBox.
Under the SelectedIndex_Changed event of the ComboBox; Enter the following code.
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Textbox1.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("EMAIL_ADDRESS"))
Textbox2.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("DEPARTMENT"))
End Sub
You Will need to declare the data table dt outside your form's load event so it can be visible to the SelectedIndex_Changed event of the combo box.
I suggest you to use BindingSource to get it done.
Try this:
1- Declare your variable type of BindingSource with events. Also, declare your dataset will be used for data.
Dim WithEvents BS As New BindingSource
Dim ds As New DataSet
2- In your Form Load Event, query your data and bind it with both Binding Source and your ComboBox control.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(ds, "myPopulatedTable")
ComboBox1.DisplayMember = "id"
ComboBox1.DataSource = ds.Tables("myPopulatedTable")
'Here the new code'
BS.DataSource = ds
BS.DataMember = "myPopulatedTable"
End Sub
3- Add a Sub Procedure to display your data into other text boxes controls.
Private Sub DISPLAYRECORD(Optional ByVal table As String = "myPopulatedTable")
TextBox1.Text = ds.Tables(table).Rows(Me.BS.Position)("column1").ToString
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column2").ToString()
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column3").ToString()
End Sub
4- In the PositionChanged event of your Binding Source, call that sub procedure (above)
Private Sub BS_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles BS.PositionChanged
DISPLAYRECORD()
End Sub
5- Finally, to sync your data with ComboBox selection, you need to change the position of that Binding Source according to the ComboBox index selection
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
BS.Position = ComboBox1.SelectedIndex
End Sub

GETTING ERROR when updating database in vb.NeT

I'M Creating A Database updater using vb.NET and database AS DATABASE1.SDF. I I WANTED TO Update the DATABASE IN DATAGridview dynamically. For UPDATING SQL COMMAND i'm USING A SQLCECOMMANDBUILDER BUT I'M GETTING A ERROR THERE AS "The DataAdapter.SelectCommand property needs to be initialized."
HERE IS MY CODE:
Imports System.Data.OleDb
Imports System.Data
Imports System.Data.SqlServerCe
Public Class Admin
Dim update As New SqlCeDataAdapter
' sql connection strings
Dim SQLCon As String = "Data Source=Database1.sdf"
Dim sqlstr As String = "Select * from Base_Plate "
Dim sqlstr1 As String = "Select * from Alloy "
Dim sqlstr2 As String = "Select * from Bead_Factor "
Dim sqlstr3 As String = "Select * from Difficulty_Factor "
Dim sqlstr4 As String = "Select * from Price_Factor "
' sql variable of base
Dim adapter As New SqlCeDataAdapter(sqlstr, SQLCon)
Dim ds As New DataSet()
' sql variable of alloy
Dim adapter1 As New SqlCeDataAdapter(sqlstr1, SQLCon)
Dim ds1 As New DataSet()
' sql variable of bead
Dim adapter2 As New SqlCeDataAdapter(sqlstr2, SQLCon)
Dim ds2 As New DataSet()
'sql variable of difficulty
Dim adapter3 As New SqlCeDataAdapter(sqlstr3, SQLCon)
Dim ds3 As New DataSet()
'sql variable of price
Dim adapter4 As New SqlCeDataAdapter(sqlstr4, SQLCon)
Dim ds4 As New DataSet()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
update.Update(ds)
LoadGrid()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Visible = False
LoginForm1.Visible = True
End Sub
Private Sub Admin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadGrid()
Button2.Enabled = False
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
End Sub
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
Button2.Enabled = True
End Sub
Private Sub LoadGrid()
'************** base datagrid ********************
adapter.Fill(ds, "Base_Plate")
DataGridView1.DataSource = ds.Tables(0)
DataGridView1.Rows(0).Selected = True
'***************** alloy datagrid *********************
adapter1.Fill(ds1, "Alloy")
DataGridView2.DataSource = ds1.Tables(0)
DataGridView2.Rows(0).Selected = True
'***************** bead datagrid *********************
adapter2.Fill(ds2, "Bead_Factor")
DataGridView3.DataSource = ds2.Tables(0)
DataGridView3.Rows(0).Selected = True
'***************** difficulty datagrid *********************
adapter3.Fill(ds3, "Difficulty_Factor")
DataGridView4.DataSource = ds3.Tables(0)
DataGridView4.Rows(0).Selected = True
'***************** Price datagrid *********************
adapter4.Fill(ds4, "Price_Factor")
DataGridView5.DataSource = ds4.Tables(0)
DataGridView5.Rows(0).Selected = True
update.UpdateCommand = New SqlServerCe.SqlCeCommandBuilder(update).GetUpdateCommand
End Sub
You're doing it wrong. Firstly, as the error message states, you haven't set the SelectCommand of the data adapter that you're passing to the command builder constructor. Here's the relevant snippets from your code:
Dim update As New SqlCeDataAdapter
update.UpdateCommand = New SqlServerCe.SqlCeCommandBuilder(update).GetUpdateCommand
As you can see, nowhere do you provide a SQL SELECT statement so how is the command builder supposed to know how to build the other commands?
Secondly, even if the adapter was properly configured, this is wrong:
update.UpdateCommand = New SqlServerCe.SqlCeCommandBuilder(update).GetUpdateCommand
You DO NOT have to get the commands from the command builder and assign them to the properties of the data adapter. The only reason to do that is if you want to edit them, which you do not. The proper way to create a command builder is on the line immediately after you create the data adapter, e.g.
Dim myDataAdapter As New SqlCeDataAdapter(query, myConnection)
Dim myCommandBuilder As New SqlCeCommandBuilder(myDataAdapter)
That's it. You create it once and once only and then the data adapter will just work when you call Update. There's no creating a new one each time you save and there's no getting and assigning of commands.

Populating Combo-box2 from value selected in combo-box1

First Combo-box has student admin numbers. When a number is selected the next combo-box should reveal the list of classes for that student. However when a value is selected the second combo-box doesn't show anything.
AdminNo is stored in both Student and ClassEnrollment tables in the database.
Imports System.Data.OleDb
Public Class AddReport
Dim cn As New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=C:\ProjectDatabase.mdb")
Dim daa As New OleDbDataAdapter()
Dim dt As New DataTable()
Private Sub btnReturn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnReturn.Click
Me.Close()
Startup.Show()
End Sub
Private Sub AddReport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
StudentNameAdd()
End Sub
Sub StudentNameAdd()
cn.Open()
daa.SelectCommand = New OleDbCommand("Select AdminNo from Student", cn)
daa.Fill(dt)
CBStudent.Items.Clear()
Dim r As DataRow
For Each r In dt.Rows
CBStudent.Items.Add(r(0).ToString)
Next
cn.Close()
End Sub
Private Sub CBStudent_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CBStudent.SelectedIndexChanged
dt.Reset()
Dim StudentAdminNo As Integer = CBStudent.SelectedValue
cn.Open()
daa.SelectCommand = New OleDbCommand("Select ClassCode from ClassEnrollment Where AdminNo=" & StudentAdminNo, cn)
daa.Fill(dt)
CBClass.Items.Clear()
Dim r As DataRow
For Each r In dt.Rows
CBClass.Items.Add(r(0).ToString)
Next
cn.Close()
End Sub
Any help pushing me in the right direction will be greatly appreciated.
What about binding the DataTable to the ComboBox by setting the Combobox's DataSource property to the DataTable?
EDIT: i've tested your code and it works fine if you change
Dim StudentAdminNo As Integer = CBStudent.SelectedValue
to
Dim StudentAdminNo As Integer = CBStudent.SelectedItem

DataGridView and BindingSource timer issue

I have a DataGridview that displays the data and a TextBox that allows me to filter the BindingSource with an SQL query to display the data based on the input string. This is all working fine apart from once I have filtered the DataGridView the timer function I have is resetting it back so all the data is being displayed again. The timer is set on a 1000ms basis, so it will show the filtered result for a second, then revert back.
Heres my code:
Imports System.Data.OleDb
Public Class Form1
Dim duraGadgetDB As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Dave\Documents\duraGadget.mdb;"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sql As String = "SELECT * FROM duragadget"
Dim connection As New OleDbConnection(duraGadgetDB)
Dim dataadapter As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "dura")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "dura"
DataGridView1.Columns(5).Width = 300
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
insert.Show()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim currentRowID As Integer
Dim scrollPosition As Integer = DataGridView1.FirstDisplayedScrollingRowIndex
Try
If DataGridView1.CurrentRow IsNot Nothing Then
currentRowID = DataGridView1.CurrentRow.Index
Dim sql As String = "SELECT * FROM duragadget"
Dim connection As New OleDbConnection(duraGadgetDB)
Dim dataadapter As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "dura")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "dura"
DataGridView1.CurrentCell = DataGridView1.Item(1, currentRowID)
End If
Catch ex As Exception
End Try
DataGridView1.FirstDisplayedScrollingRowIndex = scrollPosition
End Sub
Private Sub txtSearchOnSku_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearchOnSku.TextChanged
Dim currentRowID As Integer
Dim scrollPosition As Integer = DataGridView1.FirstDisplayedScrollingRowIndex
Try
If DataGridView1.CurrentRow IsNot Nothing Then
currentRowID = DataGridView1.CurrentRow.Index
Dim sql As String = "SELECT * FROM duragadget"
Dim connection As New OleDbConnection(duraGadgetDB)
Dim dataadapter As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
Dim dsView As New DataView
Dim bs As New BindingSource()
connection.Open()
dataadapter.Fill(ds, "dura")
connection.Close()
dsView = ds.Tables(0).DefaultView
bs.DataSource = dsView
bs.Filter = "skuNo LIKE'" & txtSearchOnSku.Text & "*'"
DataGridView1.DataSource = bs
DataGridView1.CurrentCell = DataGridView1.Item(1, currentRowID)
End If
Catch ex As Exception
End Try
DataGridView1.FirstDisplayedScrollingRowIndex = scrollPosition
End Sub
End Class
Can anyone tell me how to stop this happening?
Assuming you mean that, if you have entered a value in your text box to filter your results, that you then don't want you timer to fire and unfilter them...
You can either, check the contents of the TextBox in the Timer1_Tick routine;
If txtSearchOnSku.Text <> "" Then Exit Sub
Or you can disable your timer in the txtSearchOnSku_TextChanged routine;
If txtSearchOnSku.Text <> "" Then
Timer1.Stop
Else
Timer1.Start
End If
Or, if you want to update your results once a second, based on you search, you can include the Filtering code in your Timer1_Tick routine.
As a quick point, you have alot of repeated code there. It may be worthwhile refactoring the repeated code out into another sub.

SQL connection error showing INVALID OBJECT NAME

I have done follwing coding but it shows error
Invalid object name 'sanket'
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim da As SqlDataAdapter
Dim ds As New DataSet
Dim str As String
Private Sub ConnectToSQL()
Try
con.ConnectionString = "Data Source=SA_N_KET-PC\SQLEXPRESS;Initial Catalog=repeat;Integrated Security=true;"
con.Open()
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
'DoNothing.
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'CryrptDataSet.sanket' table. You can move, or remove it, as needed.
Me.SanketTableAdapter.Fill(Me.CryrptDataSet.sanket)
ConnectToSQL()
End Sub
Public Sub exe()
str = "insert into sanket(n)values ('" & TextBox1.Text & "')"
da = New SqlDataAdapter(Str, con)
da.Fill(ds, "sanket")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
exe()
End Sub
End Class