Displaying data in Gridview in VB - vb.net

I want to display data from database in DataGridView...This is my code...Its not working...Can anyone help me wat to do......
Dim DBCONSRT, QRYSTR As String
Dim strSQL, skunbr As String
Dim DBCON, myConn, myCommand, rs As Object
Dim NoOfRecords As Long
skunbr = TextBox1.Text
rs = CreateObject("ADODB.Recordset")
Const DB_CONNECT_STRING = "Provider=MSDASQL.1;Persist Security Info=False;User ID=cpa5k;Data Source=NP1;DSN=NP1;UID=user;PASSWORD=pass;SDSN=Default;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=QA1MM;"
myConn = CreateObject("ADODB.Connection")
myCommand = CreateObject("ADODB.Command")
myConn.Open(DB_CONNECT_STRING)
myCommand.ActiveConnection = myConn
myCommand.CommandText = "update QA1MM.STRSK_OH set OH_QTY = 250 where SKU_NBR = 100013 and STR_NBR = 116;"
myCommand.Execute()
strSQL = "select * from QA1MM.STRSK_OH where SKU_NBR = " & skunbr & " with ur FETCH FIRST 10 ROWS ONLY;"
rs.Open(strSQL, myConn)
DataGridView1.DataSource = rs
DataGridView1.Refresh()
myConn.Close()

Instead of assigning a ADODB.RecordSet directly to the datasource of datagridview like that, first convert/fill the recordset values to a dataset like below
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter
Dim myDS As DataSet = New DataSet
myDA.Fill(myDS, rs, "MyTable")
DataGridView1.DataSource = myDS.Tables(0)
DataGridView1.Refresh()

This is the classic VB way. Not .net
Please refer this MSDN link

Related

Retreiving Sharepoint List Data using vb.net

I want to retrieve SharePoint list data using VB.NET.
Below Code is for reference:-
Public Const roleGuid As String = "{8405ef03-40fl-4fan-8dl2-cf7kll1b8c1e}"
Public Const sharepointSite As String = "https://mysharepointsite.com/sites/resourceview.aspx"
Public Function getSharepointList()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConn As String
Dim sSql As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=1;RetrieveIds=Yes;" & _
"DATABASE=" & sharepointSite & ";" & _
"LIST=" & roleGuid & ";"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
With cn
.ConnectionString = sConn
.Open
End With
sSql = "SELECT * FROM [Student list] as [Student List];"
rs.Open sSql, cn, adOpenStatic, adLockOptimistic
ThisWorkbook.Worksheets("Sheet1").Range("A2").CopyFromRecordset rs
End Function
Below is error screenshot that gets popup
Any method or suggestion would be helpful.
I have found out a way to retrieve data from SharePoint list using vb.net
Public Function retrieveData()
'ADD FOLLOWING REFERENCES:-
'Microsoft ActiveX Data Objects 2.8 Library
'DECLARING CONNECTION AND RECORDSET OBJECTS, SQLQUERY STRING VARIABLE.
Dim cnt As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sqlQuery As String
'SETTING UP CONNECTION AND RECORDSET OBJECTS.
cnt = New ADODB.Connection
rs = New ADODB.Recordset
'HERE STUDENT LIST IS YOUR SHAREPOINT LIST NAME.
sqlQuery = "Select * from [Student List];"
'SETTING CONNECTION STRING TO CONNECTION OBJECT AND OPENING CONNECTION.
With cnt
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=2;RetrieveIds=Yes;DATABASE=https://mysharepointlist.com/sites/;LIST={Your List GUID};"
.Open()
End With
'OPENING RECORDSET.
rs.Open(sqlQuery, cnt, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly)
'FILLING DATATABLE WITH THE HELP OF DATA ADAPTER.
Dim myDa As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
Dim myDs As DataTable = New DataTable
myDa.Fill(myDs, rs)
'FILLING DATAGRIDVIEW WITH DATATABLE AS DATASOURCE.
DataGridView1.Datasource = myDs
'CHECKS IF CONNECTION OBJECTS AND RECORDSET OBJECT IS IN OPEN STATE IF YES THEN IT WILL CLOSE AND DEREFERENCE THEM.
If CBool(rs.State And ADODB.ObjectStateEnum.adStateOpen) = True Then rs.Close()
rs = Nothing
If CBool(cnt.State And ADODB.ObjectStateEnum.adStateOpen) = True Then cnt.Close()
cnt = Nothing
End Function

Datagridview WHERE SQL Error

I'm trying to automatically fill a datagridview upon loading. This is what I have so far
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Downloads\RailwayDatabase2.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView2.DataSource = view
When I attempt this, I am met with an error reading
Cannot find table 0.
You must fill the dataset first.
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
da.Fill(ds)
Dim view As New DataView(tables(0))
This might help. Keep it simple.
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Downloads\RailwayDatabase2.accdb"
Dim MyConn As New OleDbConnection(connString)
Dim da As OleDbDataAdapter
Dim ds As DataSet
--For error handling, do this
Try
'Open the connection
MyConn.Open()
'Fill the dataset
da = New OleDbDataAdapter("Select * from tbl_shifts WHERE EmployeeName = '" & EmployeeLogin.usersname & "' AND Completed = True", MyConn)
ds = New DataSet
da.Fill(ds)
'Fill datagridview
DataGridView2.DataSource = ds.Tables(0)
'Close the connection
MyConn.Close()
Catch ex As Exception
'Make sure connection is closed
If MyConn.State <> ConnectionState.Closed Then MyConn.Close()
End Try
And of course, you will put second group of code in Form_Load Event.

How can I change this code to SqlConnection?

Can anyone change this code to SqlConnection?
Dim Db As ADODB.Connection
Dim rs As ADODB.Recordset
Set Db = New ADODB.Connection
Db.ConnectionString = GetConnectString & AppPath & "schedule.mdb"
Call Db.Open
Set rs = New ADODB.Recordset
Set rs = Db.Execute("select * from tbl_Schedule where StartDate = #1/1/2002#")
While Not rs.EOF
Call Me.Schedule1.ScheduleItems.Add("", #1/1/2002#, rs!StartTime, _
rs!Length, rs!Description, "")
Call rs.MoveNext
Wend
Please find the below snippet which will helps you to get data from sql database. You can alter the script with your values. Import System.Data.SqlClient namespace to work with SqlConnection
Dim connection As New SqlConnection("Server=.\sqlexpress;Integrated security=sspi;database=Automation")
Dim query As String = "Select * from Heads"
If connection.State = ConnectionState.Closed Then connection.Open()
Using cmd As New SqlCommand(query, connection)
Dim reader As SqlDataReader = cmd.ExecuteReader
While reader.Read
ListBox1.Items.Add(reader("HeadName").ToString)
End While
reader.Close()
connection.Close()
End Using

Updating database from data in Gridview in VB

This is the code for displaying data from database to gridview....If i am doing any changes in GridView and it has to update in database...I dont know how to do it...Can anyone help me....
Dim DBCONSRT, QRYSTR As String
Dim strSQL As String
Dim DBCON, myConn, myCommand, rs As Object
Dim NoOfRecords As Long
rs = CreateObject("ADODB.Recordset")
Const DB_CONNECT_STRING = "Provider=MSDASQL.1;Persist Security Info=False;User ID=cpa5k;Data Source=NP1;DSN=NP1;UID=cpa5k;PASSWORD=pass;SDSN=Default;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=QA1MM;"
myConn = CreateObject("ADODB.Connection")
myCommand = CreateObject("ADODB.Command")
myConn.Open(DB_CONNECT_STRING)
myCommand.ActiveConnection = myConn
strSQL = "select * from QA1MM.STRSK_OH FETCH FIRST 10 ROWS ONLY with ur;"
rs.Open(strSQL, myConn)
Dim myDA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
Dim myDS As DataSet = New DataSet
myDA.Fill(myDS, rs, "MyTable")
DataGridView1.DataSource = myDS.Tables(0)
DataGridView1.Refresh()
myConn.Close()
I am trying this method.but it is not working
Dim myDA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
Dim myDS As DataSet = New DataSet
myDA.Fill(myDS, rs, "MyTable")
ds = DataGridView1.DataSource
myDA.Update(ds)
I changed like this:
Dim DBCONSRT, QRYSTR As String
Dim strSQL As String
Dim DBCON, myConn, myCommand, rs As Object
Dim ds As DataSet = New DataSet
rs = CreateObject("ADODB.Recordset")
Const DB_CONNECT_STRING = "Provider=MSDASQL.1;Persist Security Info=False;User ID=cpa5k;Data Source=NP1;DSN=NP1;UID=cpa5k;PASSWORD=mexico13;SDSN=Default;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Initial Catalog=QA1MM;"
myConn = CreateObject("ADODB.Connection")
myCommand = CreateObject("ADODB.Command")
myConn.Open(DB_CONNECT_STRING)
myCommand.ActiveConnection = myConn
Dim myDA As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
Dim myDS As DataSet = New DataSet
Dim dtable As DataTable = New DataTable()
myDA.UpdateCommand = New SqlClient.SqlCommand("UPDATE QA1MM.STRSK_OH set OH_QTY = 10 WHERE SKU_NBR = 108011", myConn)
' myDA.UpdateCommand.Parameters.Add("#OH_QTY", OleDb.OleDbType.VarChar, 15, "OH_QTY")
' myDA.UpdateCommand.Parameters.Add("#SKU_NBR", OleDb.OleDbType.VarChar, 15, "SKU_NBR")
' myDA.UpdateCommand.Parameters(0).SourceVersion = DataRowVersion.Current
' myDA.UpdateCommand.Parameters(1).SourceVersion = DataRowVersion.Current
dtable = DataGridView1.DataSource
myDA.Update(dtable)
myConn.Close()
But it is giving error like "Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface."
I changed the connection string like:
Provider=MSDASQL.1;Persist Security Info=False;Data
Source=NP1;DSN=NP1;SDSN=Default;HST=ibslnpb1.sysplex.homedepot.com;PRT=4101;Integrated
Security = True;Initial Catalog=QA1MM;
Its not working.The error is "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.".....Sorry i dont know how to change.....
You write like follow
myConn.Open(DB_CONNECT_STRING)
myDA.Update(ds.Tables(0))
myConn.Close()
EDIT:
Dont take the datasource of DataGridView1 into a dataset, instead take into a DataTable as follows
Dim dtable As New DataTable()
dtable = DataGridView1.DataSource
and update the table with DataAdapter as
myConn.Open(DB_CONNECT_STRING)
myDA.Update(dtable)
myConn.Close()
Refer to this link How to write UpdateCommand to OleDBDataAdapter
Try this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DataSet1.Tables("employee").AcceptChanges()
Dim i As Integer
Dim cmdbuilder As New OdbcCommandBuilder(odbcadptr)
i = odbcadptr.Update(odbcds, "customer")
MsgBox("Updated Rows: " & i)
End Sub

Using SQLDataReader instead of recordset

I am new to this and had this question. Can I use SQLDataReader instead of a Recordset. I want to achieve the following result in an SQLDataReader.
Dim dbConn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sqlstr As String = "SELECT Name,Status FROM table1 WHERE id=" + item_id.Value.ToString
rs.Open(SQL, dbConn)
While Not rs.EOF
txtName.Text = rs.Fields.Item("Name").Value
ddlstatus.SelectedIndex = 1
rs.MoveNext()
End While
rs.Close()
rs = Nothing
dbConn.Close()
dbConn = Nothing
Can I replace recordset with SQLDataReader and if I can can you please show me the changes in code?
Its highly recommend that you use the using pattern:
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New SqlConnection(sConnection)
Con.Open()
Using Com As New SqlCommand("Select * From tablename", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txtName.Text = RDR.Item("Name").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
You will have to swap out a few things, something similar to the following.
Here is an example, you will need to modify this to meet your goal, but this shows the difference.
I also recommend using a "Using" statement to manage the connection/reader. Also, a parameterized query.
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Dim objCommand As New SqlCommand
objCommand.CommandText = "Select * From tablename"
objCommand.Connection = New SqlConnection(sConnection)
objCommand.Connection.Open()
Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()
If objDataReader.HasRows Then
Do While objDataReader.Read()
Console.WriteLine(" Your name is: " & Convert.ToString(objDataReader(0)))
Loop
Else
Console.WriteLine("No rows returned.")
End If
objDataReader.Close()
objCommand.Dispose()
Dim rdrDataReader As SqlClient.SqlDataReader
Dim cmdCommand As SqlClient.SqlCommand
Dim dtsData As New DataSet
Dim dtbTable As New DataTable
Dim i As Integer
Dim SQLStatement as String
msqlConnection.Open()
cmdCommand = New SqlClient.SqlCommand(SQLStatement, msqlConnection)
rdrDataReader = cmdCommand.ExecuteReader()
For i = 0 To (rdrDataReader.FieldCount - 1)
dtbTable.Columns.Add(rdrDataReader.GetName(i), rdrDataReader.GetFieldType(i))
Next
dtbTable.BeginLoadData()
Dim values(rdrDataReader.FieldCount - 1) As Object
While rdrDataReader.Read
rdrDataReader.GetValues(values)
dtbTable.LoadDataRow(values, True)
End While
dtbTable.EndLoadData()
dtsData.Tables.Add(dtbTable)
msqlConnection.Close()
Return dtsData