Not able to bind gridview in vb.net in desktop application - vb.net

I have a gridview in which I am assigning the dataset as datasource in my program.
My Form_Load() event is:
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New SqlConnection("Data Source=HCL-43AF369E5A0;Initial Catalog=Exam;Integrated Security=True")
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
cn.Open()
cmd = New SqlCommand("Select * from Contact", cn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds)
cn.Close()
DataGridView1.DataSource = ds
End Sub
What is the error in my code? I have debugged the code and found that the dataset fetches the data but not able to bind it to gridview.
Please help.

You have to assign a Datatable as DataGridView1.DataSource. Not the DataSet. Use ds.Tables() property.

formal ways is
Dim cn As New SqlConnection("Data Source=HCL-43AF369E5A0;Initial Catalog=Exam;Integrated Security=True")
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
cn.Open()
cmd = New SqlCommand("Select * from Contact", cn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds) // edit here like da.fill(ds, "table name")
cn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "table name"
// table name will be any not the same as in your database
Your dataset is actually a data which you get by executing your query like "select * from tablename"
even you can have more than one table in a dataset so its formal method to give datamember name.

Related

textbox AutoComplete not working after a search query

Hello there I am quite new to windows form programming, and my project requires me to do a search query on my database. I would like the option for the names that can be currently searched to be displayed when typing, however, after pressing the search button the autocomplete no longer displays when I try to look for another attribute. https://i.stack.imgur.com/Wytdy.png , https://i.stack.imgur.com/Qjy5q.png
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
MaxRows = ds.Tables("customers").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customers;"
dgvCustomerInfo.DataSource = display(msSQL, "customers")
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT DISTINCT fname FROM customers"
End With
da.SelectCommand = cmd
da.Fill(dt)
Dim r As DataRow
txtSearchName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
txtSearchName.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()
I believe your problems stem from the AutoCompleteMode. Suggest and SuggestAppend seem to fill in the text box as expected. Append seem to do nothing. I don't think this is working as intended.
I tested with a little database I have. It is Sql Server but should work the same for Sqlite. I used a bit of Linq magic to get the AutoCompleteCustomSource. A few other changes... Using...End Using blocks ensure that database objects are closed and disposed. You don't need a DataAdapter, just a DataTable and Command.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataForTextBox()
Dim strArray = dt.AsEnumerable().[Select](Function(x) x.Field(Of String)("Name")).ToArray()
TextBox5.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim MySource As New AutoCompleteStringCollection()
MySource.AddRange(strArray)
TextBox5.AutoCompleteCustomSource = MySource
TextBox5.AutoCompleteMode = AutoCompleteMode.SuggestAppend
End Sub
Private Function GetDataForTextBox() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Distinct Name From Coffees", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetSearchResults(TextBox5.Text)
DataGridView1.DataSource = dt
End Sub
Private Function GetSearchResults(name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select * From Coffees Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function

Multiple DataGridView on TabPages. vb.net

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
abc()
Refresh()
Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
Dim conn As New SqlConnection(con)
Dim Query As String = Nothing
Dim Query2 As String = Nothing
Dim Query3 As String = Nothing
Dim adapter As New SqlDataAdapter
Dim adapter1 As New SqlDataAdapter
Dim ds As New DataSet()
Dim table As New DataTable()
Dim cmd1 As New SqlCommand
Query = "Select sMessage, iAlert FROM MAS_Alert"
Query2 = "SELECT REF_AlertPlate.sPlateNo, MAS_Alert.sMessage, REF_AlertPlate.iAlert, REF_AlertPlate.dStart, REF_AlertPlate.dEnd, REF_AlertPlate.sFrameNo FROM REF_AlertPlate INNER JOIN MAS_Alert ON MAS_Alert.iAlert=REF_AlertPlate.iAlert"
Query3 = "SELECT iAlert, sMessage, dCreated, iCreatedBy FROM MAS_Alert"
Try
conn.Open()
adapter.SelectCommand = cmd
adapter.SelectCommand = New SqlCommand(Query, conn)
adapter.SelectCommand = New SqlCommand(Query2, conn)
adapter.SelectCommand = New SqlCommand(Query3, conn)
adapter.Fill(ds)
adapter.Dispose()
cmd.Dispose()
ComboBox1.Items.Clear()
DataGridView2.DataSource = ds.Tables(0)
DataGridView1.DataSource = ds.Tables(1)
ComboBox1.DataSource = Nothing
ComboBox1.Refresh()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "iAlert"
ComboBox1.DisplayMember = "sMessage"
Catch ex As Exception
End Try
conn.Close()
End Sub
How can I load the datagridView1? The only DataGridView that loads is the DataGridView2. Sorry if I'm wrong, I set the three queries in the formload. What should I do first?? The only query that loads is the Query and Query2Thank you in advance mates. Hope that you can help me.
I've created another sub for the DataGridView1 then call it in FormLoad
Sub Query3()
Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
Dim conn As New SqlConnection(con)
Dim Query3 As String = Nothing
Dim adapter As New SqlDataAdapter
Dim adapter1 As New SqlDataAdapter
Dim ds As New DataSet()
Dim table As New DataTable()
Dim cmd1 As New SqlCommand
Query3 = "SELECT iAlert, sMessage, dCreated, iCreatedBy FROM MAS_Alert"
Try
conn.Open()
adapter.SelectCommand = cmd
adapter.SelectCommand = New SqlCommand(Query3, conn)
adapter.Fill(ds)
adapter.Dispose()
cmd.Dispose()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
End Try
conn.Close()
End Sub
Problem Solved. Sorry if I made a mistake.

Error: No value given for one or more required parameters. What does this mean? How do I fix?

I'm creating a program in which users can see a table from an access database in a DataGridView.
However, when pressing "btnDisplay" the program crashes and highlights this line:
da.Fill(ds, "tblOrders")
The error reads: "No value given for one or more required parameters"
What does this mean and how do I fix it?
Here is the code:
Imports System.Data.OleDb
Public Class frmViewTables
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\SAC1 Database.mdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Private Sub btnDisplayDataGrid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayDataGrid.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from [tblOrders] where Username = #username", MyConn)
cm.Parameters.Add(New OleDbParameter("#username", OleDbType.VarChar, 255, frmLogin.SuccessfulLoginUsername))
cm.Parameters("#username").Value = frmLogin.SuccessfulLoginUsername
da.Fill(ds, "tblOrders")
Dim view As New DataView(tables(0))
source1.DataSource = view
dgvDynamic.DataSource = view
End Sub
Things seem a little messed up. I am not sure about the rest of it but this should solve your parameter problem.
Dim source1 As New BindingSource
Dim ds = New DataSet
Dim tables = ds.Tables
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\SAC1 Database.mdb")
Dim da As OleDbDataAdapter = New OleDbDataAdapter()
Dim cmd As New OleDbCommand("Select * from [tblOrders] where Username = #username", cn)
cmd.Parameters.Add("#username", OleDbType.VarChar, 255).Value = frmLogin.SuccessfulLoginUsername
da.SelectCommand = cmd
da.Fill(ds, "tblOrders")
Dim view As New DataView(tables(0))
source1.DataSource = view
dgvDynamic.DataSource = view

Login failed for user ''. error

I know that this is a duplicate post but I couldn't find my solution on that topics. I want to connect my sql file in debug folder but I got error that Login failed for user ''.
Dim connectionString As String = String.Format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\Word.mdf;Integrated Security=False;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sql As String = "SELECT * FROM test"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "test_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "test_table"
MakePivot()
connection.Close()
DataGridView2.ClearSelection()
End Sub
Could you tell me my mistake please?
Dim ds As New DataSet()
Using connection As New SqlConnection(String.Format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\Word.mdf;Integrated Security=true;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath))
connection.Open()
Using command As New SqlCommand("SELECT * FROM test", connection)
command.CommandTimeout = 0
Using da As New SqlDataAdapter(command)
da.Fill(ds)
End Using
End Using
End Using
DataGridView1.DataSource = ds
MakePivot()
DataGridView2.ClearSelection()
Try this code, need to set "integrated security=true"

Updating a remote Access server

In the creation of my program, i have found it will be more reliable to supply a local database with the package, rather then connecting to the remote DB for each instance.
Below is my idea on how to do it, however i wish for it to happen automatically for each distinct host that it finds, rather than selecting each member and pressing the button. This is something that i do not know how to achieve.
Imports System.Data.OleDb
Public Class Form1
Dim con as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='.\localDB.accdb'")
Dim rem as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='\\server\remote.accdb'")
dim da as new oledbdataadaptor
dim dt as new datatable
dim dt2 as new datatable
Dim Str as string
Dim cmd as new oledbcommand(str, con)
Private Sub Form1_load
con.open()
da.SelectCommand = New OleDbCommand("select distinct Host from Logs")
da.fill(dt)
con.close
Combobox1.datasource = dt
Combobox1.displaymember = "Host"
End Sub
Private Sub button1_click
con.open()
Dim cmd As New OleDbCommand("select * from local where host=#host;", con)
cmd.parameters.addwithvalue("#host", combobox1.text.tostring)
da.fill(dt2)
con.close()
rem.open()
Dim cmd1 As New OleDbCommand("update remote set col1=#col1 where ID=#ID;", con)
cmd1.parameters.addwithvalue("#col1", dt2.rows(0).item(1).tostring)
cmd1.parameters.addwithvalue("#ID", dt2.rows(0).item(0).tostring)
rem.close()
End Sub
End Class
Any idea's would be appreciated.
*As a note, i realise that JET offers the sync ability however the database is required to be in the 2007-10 format, so ACE is the only option.
First of all OleDbCommand does not accept named parameters, so you need to reference them with ? and pass the parameters in the same order that they appear.
Dim cmd As New OleDbCommand("select * from local where host = ?", con)
cmd.parameters.Add(combobox1.Text.ToString)
Once done, you'll need to fill the DataSet with the results of the SQL sentence
Dim DA As New OleDbDataAdapter(cmd)
Dim DS As New DataSet
DA.Fill(DS, "hosts")
UPDATE
In order to have an equivalent code as yours, I would do something like this
Imports System.Data.OleDb
Public Class Form1
Dim con as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='.\localDB.accdb'")
Dim rem as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='\\server\remote.accdb'")
dim dt as New DataTable
Dim Str as String
Dim cmd as New OleDbCommand(str, con)
Private Sub Form1_load
con.open()
da.SelectCommand = New OleDbCommand("select distinct Host from Logs")
da.fill(dt)
con.close
For Each DR as DataRow In DT.Rows
con.open()
Dim cmd As New OleDbCommand("select * from local where host= ? ", con)
cmd.Parameters.Add(DR.Item(0))
Dim DA As New SqlClient.SqlDataAdapter(cmd)
Dim DS As New DataSet
da.Fill(DS,"hosts")
con.close()
rem.open()
Dim cmd As New OleDbCommand("update remote set col1=? where ID=?", rem)
cmd.Parameters.Add(DS.Tables("hosts").Rows(0).Item(1).ToString)
cmd.Parameters.Add(DS.Tables("hosts").Rows(0).Item(0).ToString)
cmd.ExecuteNonQuery()
rem.close()
Next
End Sub
End Class