I am trying to retrieve data from SQL Server into my form. I am trying with the below code. When I run this I get the first item or row but I am unable load the rest of the items into my listview . Can someone help to solve my issue?
Sub GetInvoiceDetails()
Dim Inv As New petClass
Dim dt As DataTable = Inv.GetInvoiceDetailsbyNo(txtInvoiceNo.Text)
If dt.Rows.Count > 0 Then
For Each row In dt.Rows
srno += 1
Dim lstitem = Lstview.Items.Add(srno)
lstitem.SubItems.Add(dt.Rows(0).Item("ItemName").ToString)
lstitem.SubItems.Add(dt.Rows(0).Item("SellingPrice".ToString)).ToString()
Next
End If
'clearcontrols
End Sub
You're always using the first row in the DataTable with dt.Rows(0).
Instead:
For Each row As DataRow In dt.Rows
srno += 1
Dim lstitem = Lstview.Items.Add(srno)
lstitem.SubItems.Add(row.Field(of String)("ItemName"))
lstitem.SubItems.Add(row.Field(Of String)("SellingPrice"))
Next
First thing i see is that you're referencing only the first row of your datatable.
Try this:
Sub GetInvoiceDetails()
Dim Inv As New petClass
Dim dt As DataTable = Inv.GetInvoiceDetailsbyNo(txtInvoiceNo.Text)
If dt.Rows.Count > 0 Then
For Each row In dt.Rows
srno += 1
Dim lstitem = Lstview.Items.Add(srno)
lstitem.SubItems.Add(row.Items("ItemName").ToString)
lstitem.SubItems.Add(row.Items("SellingPrice".ToString)).ToString()
Next
End If
'clearcontrols
End Sub
Next thing, I'm a bit confused by what you're trying to do here:
lstitem.SubItems.Add(row.Items("SellingPrice".ToString)).ToString()
You shouldn't need the second ToString(), no??
Related
I'm trying to copy rows from one DataTable to another, but only copy rows where the data is yet to be saved to the database table.
The SQL side of this is working fine, it's returning the correct number of columns, however, when I add the rows that were found to my second DataTable and set it as the DataSource for my grid, there is no data displayed, although there is a row that has been added, since the row selector is visible.
What am I doing wrong, and why isn't the data being copied with it?
lftable = New DataTable
Try
For Each dc As DataColumn In lineTable.Columns
lftable.Columns.Add()
Next
Dim ds As New DataSet
For Each row As DataRow In lineTable.Rows
Dim da As New OleDbDataAdapter("SELECT * FROM [Order_Freight] WHERE [Order_Number] = ? AND [Product_Code] <> ?", con)
da.SelectCommand.Parameters.Add("#num", OleDbType.Integer).Value = orderNum
da.SelectCommand.Parameters.Add("#prod", OleDbType.VarChar).Value = row.Item("Product_Code")
da.Fill(ds)
For Each dr As DataRow In ds.Tables(0).Rows
Dim nRow = lftable.Rows.Add()
nRow.ItemArray = dr.ItemArray()
Next
Next
ugProducts.DataSource = lfTable
Screenshot of the grid after assigning it the DataSource
Fill the columns correctly:
For Each dc As DataColumn In lineTable.Columns
lftable.Columns.Add(new DataColumn(dc.ColumnName, dc.DataType));
Next
You can use the overload of the Row.Add function which allows you provide the ItemArray directly:
For Each dr As DataRow In ds.Tables(0).Rows
lftable.Rows.Add(dr.ItemArray)
'nRow.ItemArray = dr.ItemArray() <-- remove
Next
Instead of this code :
' For Each dc As DataColumn In lineTable.Columns
' lftable.Columns.Add() >
' lftable.Columns.Add(dc)
' Next
Use DataTable.Clone() to copy only the columns in a lineTable to lftable
lftable = lineTable.Clone();
And then
For Each dr As DataRow In ds.Tables(0).Rows
lftable.Rows.Add( dr.ItemArray)
Next
Can anyone please help, tell me why the data from database did not display in the rows? Instead "System.Collections.ArrayList" and "System.Data.DataRow" are displayed.
Dim myArray(4, 4) As String
For Each dtrow As DataRow In dt.Rows
list.Add(dtrow)
Next
For i = 0 To myArray.GetUpperBound(0)
If i = 0 Then
html.Append("<tr>")
ElseIf (i > 0 And i < 5) Then
html.Append("</tr>")
html.Append("<tr>")
For j = 0 To myArray.GetUpperBound(1)
Dim no = 0
'insert the code i mentioned below here'
no += 1
Next ' j'
End If ' if in i'
Next ' i
When i tried running using this 1 line below inserted to the above code, it displays System.Collections.ArrayList in the rows.
html.Append(list)
But when i tried running using this 1 line below inserted to the above code, it displays System.Data.DataRow in the rows.
html.Append(list(no))
========================================================================
Another method i tried, when i tried running using this line "html.Append(dt.Rows.Item(0)(0))" , it displays the correct data, but when i tried to do a loop to increase the number of columns and rows, it shows the same value of data. as though as the 'rw' and 'col' loop didnt work.
For j = 0 To myArray.GetUpperBound(1)
Dim no = 0
For rw = 0 To 5
Dim rno = 0
For col = 0 To 5
Dim cno = 0
no += 1
html.Append(dt.Rows.Item(rno)(cno))
cno += 1
Next
rno += 1
Next
Next 'j'
You already got a correct result when you used html.Append(dt.Rows.Item(0)(0)) - now you need write correct loop.
Noticed that you have DataTable instance - use this for looping through all rows and columns
For Each row As DataRow in dt.Rows
html.Append("<tr>")
For Each column in dt.Columns
html.Append("<td>")
html.Append(row(column.Ordinal))
html.Append("</td>")
End For
html.Append("</tr>")
End For
When working with xml I like using LINQ to Xml with XElement type, with those I can be sure that my xml structure is correct during compiling.
Visual basic have a nice feature which c# does not - XML Literals (Visual Basic)
Dim table As XElement = <table></table>
For Each row As DataRow in dt.Rows
Dim tr As XElement = <tr></tr>
For Each column in dt.Columns
Dim td As XElement = <td></td>
td.Value = row(column.Ordinal).ToString()
tr.Add(td)
End For
table.Add(tr)
End For
So, Access database has two columns 1st is seller name (SELLER) and second is it's code (CODE). Access database is database with all SELLER CODEs.
DGV is populated from other source and consists of some of CODEs from Access database.
DGV has one column with codes.
I would like to create and populate new column (SELLERNAME) in DGV with SELLER names based on DGV codes and Access database CODEs.
I am going to give an example since it's hard for me to explain this better :
DGV : Column 0, 1st value = 0055, in Access database code 0055 corresponds to the name John
so I would like to put name "John" in DGV Column1, 1st value, nest to "0055" and so on
Here is my code so far :
DataGridView1.Columns.Add("SELLERNAME", "SELLERNAME") '1
Dim cn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Dim odr As OleDb.OleDbDataReader
Dim strSQL As String
cn = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.MDB")
strSQL = "SELECT SELLER, CODE FROM SCBASE"
cn.Open()
cmd = New OleDb.OleDbCommand(strSQL, cn)
odr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While odr.Read
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = odr.GetValue(1).ToString()
Next
Loop
I don't know what to do next after line For i As Integer = 0 To DataGridView1.Rows.Count - 1.
EDIT :
I think I am close but I need help with one line of code :
Using sqlconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.mdb")
Using sqlcmd = New OleDbCommand("Select SELLER, CODE From SCBASE Where CODE = #CODE ", sqlconn)
sqlcmd.Parameters.AddWithValue("#CODE ", DataGridView1.Rows(i).Cells(0).Value) 'HOW TO ADD THIS LINE IN LOOP BELOW
sqlconn.Open()
Dim result = sqlcmd.ExecuteReader()
Do While (result.Read())
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = (result("DOBAVLJAC"))
Next
Loop
End Using
End Using
I had no success with a trial and error. I am trying to put this line sqlcmd.Parameters.AddWithValue("#CODE ", DataGridView1.Rows(i).Cells(0).Value) in loop below but I am getting all sorts of error.
Yes, you are very close. You just need to .Add the Parameter outside the loop and then set its .Value inside the loop like this
Using sqlconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.mdb")
sqlconn.Open()
Using sqlcmd = New OleDbCommand("Select SELLER, CODE From SCBASE Where CODE = ?", sqlconn)
sqlcmd.Parameters.Add("?", OleDbType.VarWChar, 255)
sqlcmd.Prepare()
For i As Integer = 0 To DataGridView1.Rows.Count - 1
sqlcmd.Parameters(0).Value = DataGridView1.Rows(i).Cells(0).Value
Using result = sqlcmd.ExecuteReader()
If result.Read() Then
DataGridView1.Rows(i).Cells(1).Value = result("SELLER")
End If
End Using
Next
End Using
End Using
Fist column of listview is populated from database (database column name KONTO - only values that starts with 2020-), second column of the listview should be populate from corresponding items to KONTO from same database column NAZIV into second column of the listview.
Description is in column NAZIV in databsase
I've been experimenting with this all day and didn't have any success.
Here is the code I have so far :
ListView1.View = System.Windows.Forms.View.Details
ListView1.Columns.Add("COL1", 100, HorizontalAlignment.Left) 'KONTO
ListView1.Columns.Add("COL2", 160, HorizontalAlignment.Left) 'NAZIV
Dim FilePath As String = "W:\GLAVNI\KOR14\"
Dim DBF_File As String = "MATIKGL"
Dim ColName As String = "KONTO"
'Dim naz As String
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT * FROM MATIKGL ORDER BY KONTO, NAZIV", con)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
While (reader.Read())
Me.ListView1.Items.Add(reader("KONTO"))
'LOOP BELOW SELECTS ALL ITEMS THAT STARTS WITH 2020-
For i = 0 To ListView1.Items.Count - 1
If ListView1.Items(i).ToString.Contains("2020-") Then
Else
ListView1.Items.Remove(ListView1.Items(i))
End If
Next
End While
Else
End If
End Using
End Using
con.Close()
End Using
Thanks.
UPDATE
To be more clear, here is the screen from database.
Only items starting with 2020- (1) should populate first column of listview, and second column should be populated with "2020-" description from column NAZIV (2).
Each LV Item has a collection of SubItems associated with it. The subItems show as columns in the Details view:
Dim lvi As ListViewItem ' scratch var for adding items
Dim tmp As String
Using cmd As New OleDbCommand("SELECT * FROM MATIKGL ORDER BY KONTO, NAZIV", con)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
While (reader.Read())
' Db rdr returns Object, cast to string
tmp = reader.Item("KONTO").ToString
' no need to loop - just use the scratch vars
' only adding if it contains 2020
If tmp.Contains("2020-") Then
lvi = New ListViewItem
lvi.Text = tmp
' add the sub item
lvi.SubItems.Add(reader("NAZIV").toString)
ListView1.Items.Add(lvi)
End If
End While
End If
End Using
you can get rid of the tmp var using reader.Item("KONTO").ToString.Contains("2020")...the above is for clarity
I am inserting values in datagrid from MS-SQL server. I got a text box from which i wanted to perform search operation , but the thing is i haven't used data set.
the question is How do i search for values in datagrid without using data set in vb.net.
Here is my code fr filling up data grid view.
dim i as integer = 0
con.ConnectionString = "Data Source=MY_CONNECTION_STRING "
Dim cmd As New SqlCommand("selct ID, Name From tbl_name where 1=1 Order by Name ASC", con)
con.Open()
' Execute Query
Dim reader As SqlDataReader = cmd.ExecuteReader()
' Try
While reader.Read()
DataGridView10.Rows.Insert(i, New String() {reader(0), reader(1).ToString})
i = i + 1
End While
You can put this in a click event per say...
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim intIndex As Integer = SearchGrid(TextBox1.Text, 0) 'Change the 0 to what column you want to search for
DataGridView1.Rows(intIndex).Selected = True 'This will select the row...'
DataGridView1.CurrentCell = DataGridView1.Rows(intIndex).Cells(0) 'This ensures that the arrow will move if you have row headers visible. In order to select the cell change the zero to the column your searching to match up top
End Sub
Here's the function...
Private Function SearchGrid(ByVal strItem As String, ByVal intColumn As Integer) As Integer
Dim intIndex As Integer = 0
For i As Integer = 0 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(i).Cells(intColumn).Value.ToString.Contains(strItem) Then 'Or change "Contains" to "Equals"
intIndex = i
Exit For
End If
Next
Return intIndex
End Function
This will work great for you and a great start, happy coding!
P.S. Make sure to change the datagridview name to reflect yours...