I am facing a problem displaying the records of my table on the visual basic form I have created.
This is my code :
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
myconnection = New SqlConnection("server=HOME-PC\SQLEXPRESS;uid=sa;pwd=123;database=college")
myconnection.Open()
mycommand = New SqlCommand("SELECT * from demo3)", myconnection)
Dim mySqlDataAdapter As New SqlDataAdapter(mycommand)
Dim mydsStudent As New DataSet()
mySqlDataAdapter.Fill(mydsStudent, "Student")
ra = mycommand.ExecuteNonQuery()
MessageBox.Show("Data Displayed" & ra)
myconnection.Close()
End Sub
End Class
Note: my database name is "college" , table name is "demo3" . Table contains 2 columns namely name and roll no. How to display the data in those columns on the visual basic form that I have created ?
You don't need to call execute non query. You can bind the dataset to a DataGridView. Like this
Dim DataGridView1 as new DataGridView()
DataGridView1.DataSource = mydsStudent
'Your table goes here, not sure about the exact propety name, hope it works.
DataGridView1.DisplayMember = "demo3"
Me.Controls.Add(DataGridView1)
Related
So I have been able to connect my database to VB forms, and I am also able to see the table and the fields within. But I can't figure how to make the data appear in the table because it's just blank.
I do have some data stores in the actual access database but it won't show up in my program.
Is there a particular code I need to write? This is what I have so far. The database is called the 'POS system'.
Private Sub OrdersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles OrdersBindingNavigatorSaveItem.Click
Me.Validate()
Me.OrdersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.POS_systemDataSet)
End Sub
It is usually a good idea to separate your database code from your user interface code. Create a connection and a command in a Using block so they will be closed and disposed at End Using. Pass the connection string to the constructor of the connection. Pass the CommandText and connection to the constructor of the command. Open the connection and execute the command returning a DataReader to load the DataTable.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetData()
DataGridView1.DataSource = dt
End Sub
Private Function GetData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("Select * From SomeTable;", cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
I've created the table: "tblInterni" on my sql database and made so that I can see it on a datagridview.
I am now making a search function so that if I search for a name it loads everyone with that name in the datagridview, but the query I made isn't working.
Private Sub Home_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=dbTest;User ID=pwdDb;Password=pwdDb")
Dim adapter As New SqlDataAdapter("SELECT * FROM tblInterni", conn)
Dim table As New DataTable()
adapter.Fill(table)
DataGridView1.DataSource = table
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim searchQuery As String = "SELECT * From tblInterni WHERE name like '%" & TextBox1.Text & "%'"
End Sub
form graphic
Given that you are retrieving all the data when the form loads, what you should be doing is binding your DataTable to the DataGridView via a BindingSource and then filtering that data by setting the Filter property of the BindingSource.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using adapter As New SqlDataAdapter("SELECT * FROM MyTable", "connection string here")
Dim table As New DataTable
adapter.Fill(table)
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Using
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
BindingSource1.Filter = $"MyColumn LIKE '%{TextBox1.Text}%'"
End Sub
Note that the BindingSource would be added in the designer, just like the grid.
This is still not ideal though. If the user wants to type several characters in order to filter then this code will modify the filter several times unnecessarily and actually slow them down. A better idea is to use a Timer to add a small delay before filtering that resets each time they make a change. That way, if they type several characters quickly enough, the filter will only change after the last character.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using adapter As New SqlDataAdapter("SELECT * FROM MyTable", "connection string here")
Dim table As New DataTable
adapter.Fill(table)
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Using
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'Start/reset the filter timer.
Timer1.Stop()
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
BindingSource1.Filter = $"MyColumn LIKE '%{TextBox1.Text}%'"
End Sub
You can experiment a bit with the Interval of the Timer but you should find that something around 300 milliseconds should mean that filtering still feels fast enough but typing at a reasonable speed should avoid most unnecessary intermediate filters.
After creating a table and putting data in it in the previous form, this form tries to display the report, but I am getting a blank report. What am I doing wrong?
Here is my VB 2017 code for form load event:
Imports CrystalDecisions.CrystalReports.Engine
Public Class Form5
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cryRpt As New ReportDocument
cryRpt.Load("C:\Users\Administrator\source\repos\WindowsApp3\WindowsApp3\CrystalReport4.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class
I solved my problem in the following way
Here is my modified VB 2017 code for form load event:
Dim query As String = "SELECT * FROM monAtt"
Dim cmd As New SqlCommand(query, conn1)
cmd.CommandType = CommandType.Text
conn1.Open()
Dim MyDA As New SqlClient.SqlDataAdapter()
MyDA.SelectCommand = cmd
Dim myDS As New TestDataSet1()
MyDA.Fill(myDS, "monAtt")
Dim oRpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument()
oRpt.Load("C:\Users\Administrator\source\repos\WindowsApp3\WindowsApp3\CrystalReport4.rpt")
oRpt.SetDataSource(myDS.Tables("monAtt"))
CrystalReportViewer1.ReportSource = oRpt
CrystalReportViewer1.RefreshReport()
CrystalReportViewer1.Visible = True
conn1.Close()
cmd.Dispose()
I want to load or show the data from SQL Server on a DataGridView.
The build succeeds and there's no error when I run it. There's nothing wrong in form modul_koneksi (I think) because it works on my other form (form_login)
However, nothing shows up in my DataGridView. How can I fix this?
Code:
Imports System.Data.SqlClient
Public Class FormProduk
Private Sub FormProduk_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String = "Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"
Dim connection As New SqlConnection(str)
Dim com As String = "Select * From tbl_user"
Dim dataadapter As New SqlDataAdapter(com, connection)
Dim dataset As New DataSet()
dataadapter.Fill(dataset, "tbl_user")
DataGridView1.DataSource = dataset.Tables()
End Sub
End Class
You should define which table to load in the DataGridView:
DataGridView1.DataSource = dataset.Tables("tbl_user")
You cannot set the .DataSource property with dataset.Tables. Instead you need to set it with a DataTable located in your DataSet:
DataGridView1.DataSource = dataset.Tables("tbl_user")
However I think you could simplify the code a little by getting rid of the SqlDataAdapter and loading straight into a DataTable
Dim dt As New DataTable
dt.Load(com.ExecuteReader())
DataGridView1.DataSource = dt
I would also consider implementing Using:
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
With the changes your code would look something like this:
Dim dt As New DataTable
Using con As New SqlConnection("Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"),
cmd As New SqlCommand("SELECT * FROM tbl_user", con)
con.Open()
dt.Load(cmd.ExecuteReader())
End Using
DataGridView1.DataSource = dt
Not enough info to tell, are you sure your connection string str is correct. You can try change to this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String = "Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"
Dim conn As New SqlConnection(str)
Dim cmd As String = "Select * From tbl_user"
Dim adapter As New SqlDataAdapter(cmd, conn)
Dim tabeluser As New DataSet
adapter.Fill(tabeluser)
DataGridView1.DataSource = tabeluser.Tables
End Sub
I have a VB.NET 2010 application that loads data from SQL Server to a datagridview through adapter.fill(). When I update the database it works fine but my problem is that when i use the dataview to filter the data based on combobox selection the method adapter.update(table) does not work!
Is there away to do it with the filter applied?
Private Sub cmbDepartment_SelectedIndexChanged(...)
Handles cmbDepartment.SelectedIndexChanged
Dim filter As String
Try
lblDepartmentId.Text = ds.Tables("department").Rows(cmbDepartment.SelectedIndex)(0)
filter = "dprtId = " & lblDepartmentId.Text
dvSection = New DataView(ds.Tables("section"), filter, "", DataViewRowState.CurrentRows)
table = dvSection.ToTable
dgvSections.DataSource = table
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Private Sub btnSaveDepartment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnSaveDepartment.Click
Dim cbDep As SqlCommandBuilder
Dim numRows As Integer
Try cbDep = New SqlCommandBuilder(daDep)
Me.Validate() numRows = daDep.Update(ds.Tables("section"))
MsgBox(numRows & " Rows affected.")
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
The way you are currently doing your filtering is by creating a new DataTable and binding this to your DataGridView data source. This breaks the association between the original DataSet and that table so when you call Update your changes are not recovered.
Try changing to something like the code below instead (I've left out the try catch blocks, they don't change the idea that fixes your problem).
When you first set the data source to the grid set it to a form level private dvSection field:
Public Class Form1
' Here we declare some class level variables.
'These are visible to all members of the class
Dim dvSection As DataView
Dim tableAdapter As New DataSet1TableAdapters.CustomersTableAdapter()
Dim ds As New DataSet1()
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' We fill our dataset - in this case using a table adapter
tableAdapter.Fill(ds.Customers)
dvSection = ds.Customers.DefaultView
DataGridView1.DataSource = dvSection
End Sub
' Here is the code to filter.
' Note how I refer to the class level variable dvSection
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim filter As String
lblDepartmentId.Text = ds.Tables("department").Rows(cmbDepartment.SelectedIndex)(0)
filter = "dprtId = " & lblDepartmentId.Text
dvSection.RowFilter = filter
dvSection.RowFilter = filter
End Sub
' And here is the update code referring to the class level table adapter
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
tableAdapter.Update(ds.Customers)
End Sub
End Class
One other approach that might make things easier is to introduce a binding source and set the filter on that. Either was should work fine however.