dt is a datatable from ODBC, where i need to find a specific value
LookupCode is returning correct value from DataGrid
LookupRow is returning System.NullReferenceException but i'm sure that in dt there is data that I'm looking for
Imports System.Linq
...
Dim dt As New DataTable
Dim LookupRow As DataRow
Dim LookupCode As String
If dt.Rows.Count > 0 Then
For Each row As DataGridViewRow In MagDataGridView.Rows
LookupCode = row.Cells(1).Value
LookupRow = dt.Select("'" & dt.Columns(0).ColumnName & "'='" & LookupCode & "'").FirstOrDefault
row.Cells(5).Value = LookupRow.Item(1)
Next
End If
Screenshot of Compilator
After 1st comment
If i change the line to LookupRow = dt.Select(dt.Columns(0).ColumnName & "='" & LookupCode & "'").First
then i have unable to perform '=' on System.Int32 and System.String.”
Solved with this replacement of code:
Dim fRow = From row In dt.AsEnumerable()
Where row.Field(Of String)(dt.Columns(0).ColumnName) = LookupCode
LookupRow = fRow.First
r.Cells(5).Value = LookupRow.Item(1)
Related
I have a MySQL table (variable- exchange) with a column name "symbol" and I have a list of string named "listfinalselection". I want to select all rows where the list contains the cell value of column "symbol". But I got a error that there is an error in my SQL syntax. I can't understand that error. Please help. `
Dim mysqlconn As MySqlConnection
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "server=localhost;user id=root;password=1234;database=Share"
mysqlconn.Open()
Dim sql As String = "SELECT * FROM " & exchange & " WHERE Symbol in (" & String.Concat(",", listfinalselection.Select(Function(i) $"'{i}'").ToArray()) & ");"
Dim adapter As New MySqlDataAdapter(sql, mysqlconn)
Dim datatable As New DataTable()
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Refresh()
Dim ii As Integer = 0
For Each rw As DataGridViewRow In DataGridView1.Rows
Try
DataGridView1.Rows(ii).Cells(11).Value = listeleventh(listsymbol.IndexOf(DataGridView1.Rows(ii).Cells(3).Value.ToString))
Catch
End Try
ii = ii + 1
Next
End Sub `
Here's how we can properly and securely query MySQL for a list of values:
Dim con = New MySqlConnection("server=localhost;user id=root;password=1234;database=Share")
'NOTE WELL: you still have to make sure that exchange contains no SQL!
Dim cmd As New MySqlCommand("SELECT * FROM " & exchange & " WHERE Symbol in (", con)
For i as Integer = 0 to listfinalselection.Count - 1
cmd.Parameters.AddWithValue("#p" & i, listfinalselection(i))
cmd.CommandText &= "#p" & i & ","
Next i
cmd.CommandText = cmd.CommandText.TrimEnd(","c) & ")"
Dim adapter As New MySqlDataAdapter(cmd)
Dim dt as New DataTable
adapter.Fill(dt)
Please note, before someone quotes the "Can we stop using AddWithValue already" blog, it's irrelevant to mysql
I have a datagridview1 which has 5 columns, I add to that gridview items from datagridview2, and nothing wrong with that, now when I try to take these values from Datagridview1 using 2 denominational for loop, to insert it into my sql db, it shows this error.
Index was out of range. must be non-negtive and less than the size of the collection. Parameter name index.
I hope I explained it well.
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
con.ConnectionString = "Data Source = OMAR\MSSQLSERVER01;Initial Catalog=AccountsC20;Persist Security Info=True;User ID=ofamo;"
con.Open()
cmd.Connection = con
Dim Selected = ListBox1.SelectedValue.ToString()
If Selected = "0" Then
MessageBox.Show("Make sure to select a valued product")
Else
MessageBox.Show((TextBox4.Text) + 1)
For i As Integer = 0 To DataGridView1.RowCount - 1
For j As Integer = 0 To DataGridView1.ColumnCount - 1
cmd.CommandText = "Insert into SInvoice Values('SIV-" & (TextBox4.Text) + 1 & "',0," & j + 1 & ",(select nodeno from productmast where arabic_name= '" & Selected & "')," & DataGridView1.Item(i, 2).Value & ",0.000000,'2019-04-04 13:40:00'," & DataGridView1.Item(i, 4).Value & "," & DataGridView1.Item(i, 3).Value & ",'',0,1,1,1,1,'04/04/2019 13:39:44','',1.000000,1,0,'','b',0.000000,5,0.000000," & DataGridView1.Item(i, 3).Value & ",'Nos',1.000000,'','','','','','','','','','','','','','','','','','','','','',0,3,'" & Label4.Text & "',1,1,1,1,1,1,0.000000)"
cmd.ExecuteNonQuery()
Next
Next
What way are you filling your datagridview either 1 or 2? if you are using likes of a datatable or that you could do this transfering to sql database very easily and quickly using sqlbulkcopy, but I dont know if you want it that way or if you use datatable etc.
For Each row As DataGridViewRow In DataGridView1.Rows
For j = 0 To DataGridView1.Columns.Count - 1....
Try use the for each loop see if it makes a difference
This is my filtering method.
Public Function Filter(data As DataTable)
Try
Dim str As String = "[Name] IN ("
Dim bs As New BindingSource()
bs.DataSource = dtMain
bs.Filter = dtMain.DefaultView.RowFilter
Dim dv As DataView = CType(bs.List, DataView)
Dim dt As DataTable = dv.ToTable()
If dt.Rows.Count = 0 Then
data.DefaultView.RowFilter = "[Name] = 'NULL'"
Return 0
End If
For Each dr As DataRow In dt.Rows
str = str + "'" & dr.Item("Name") & "', "
Next
str = str.Substring(0, str.Length - 2)
str = str + ")"
data.DefaultView.RowFilter = "(" & str & ")"
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Return 0
End Function
The problem is one of the names in the DataGridView has an apostrophe in it. So the filter hits the apostrophe, thinks it's its own value, then throws a syntax error because there's no comma after it. I don't know how I can get around this and I can't manipulate the data.
I'm not positive, but I'd wager the correct way to handle this (if it behaves the same way a database insertion does), is to escape the single quote with another single quote. So in your DataRow iterator, a minor change like this might be in order:
For Each dr As DataRow In dt.Rows
str = str + "'" & dr.Item("Name").Replace("'", "''") & "', "
Next
I'm reading a column of integers from an excel spreadsheet into a datagridview and it's just not working. I've tried two ways, one way using a loop and the other way using OleDb. The code just before the troublesome line uses OleDb to fill another DGV with one column from excel perfectly, so I don't know why it doesn't work the second time. Here's what I got:
Method 1---
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & FormFile & """;Extended Properties=""Excel 12.0;HDR=YES;""")
'Fill dataviewgrid1 with element symbols, string' THIS WORKS PERFECTLY!!
da = New OleDbDataAdapter("select * from [" & sheetname & "$A13:A" & lrow & "]", cn)
ds = New System.Data.DataSet
da.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
'Fill dataviewgrid2 with compositions, string' THIS DOESN"T WORK, AND I DONT GET ANY ERROR MESSAGES. NOTHING HAPPENS.
da2 = New OleDbDataAdapter("select * from [" & sheetname & "$B13:B" & lrow & "]", cn)
ds2 = New System.Data.DataSet
da2.Fill(ds2)
DataGridView2.DataSource = ds2.Table
To reiterate above, filling dgv1 is successful. Filling dgv 2 is unsuccessful, and no errors pop up or anything. Here's the other way I tried:
Method 2:
DataGridView.ColumnCount = 1
For xrow As Integer = 13 To lrow - 1
DataGridView.Rows.Add
DataGridView2.Item(0, xrow - 13).Value = xlWsheet2.Cells(xrow, 2).Value
Next
this gets me the error 'Index out of range'.
Why can't I get this to work?
I believe I found the answer to correcting method 2, above. I didn't define xlWsheet2.
I'm still not sure why method 1 didn't work.
I have a DataGridView with 2 columns. The first column is populated with folder paths and the second column is empty. Inside each folder path is a single database named DB1. I would like to extract 1 value (VALUE) from each database and then put that value next to corresponding database path, in the second column. This is the query I am using
Select CODE, VALUE from DB1 where CODE = 2419
I know how to populate a DataGridView and how to extract 1 value from the database, but with this I don't even know where to begin.
EDIT
I've managed to create working loop but don't know how to add those values to corresponding places in datagridview.
For Each row As DataGridViewRow In DataGridView1.Rows
Dim sendtroopid As String
sendtroopid = row.Cells("CODE").Value
On Error Resume Next
Dim FilePath As String = sendtroopid 'DATABASE PATH
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 CODE, VALUE FROM DB1 WHERE CODE = #CODE", con)
cmd.Parameters.AddWithValue("#CODE", "2419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
While (reader.Read())
MsgBox(reader("VALUE"))
End While
End Using
End Using
End Using
Next
EDIT 2
With code above I get all values in msgbox. Only thing left is to insert another loop to put all those values (starting with row 0) to datagridview.
If I replace msgbox with
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = (reader("VALUE"))
Next
then all rows are populated with only last value (value from last database).
EDIT 3
I've changed
value = reader.Read()
with
While (reader.Read())
value = reader("VALUE")
End While
I'm still not sure how your query works, but assuming it does, I've changed your code.
For Each row As DataGridViewRow In DataGridView1.Rows
Dim sendtroopid As String
sendtroopid = row.Cells("CODE").Value
On Error Resume Next
Dim FilePath As String = sendtroopid 'DATABASE PATH
Dim value as string = "" ' declare a string variable to hold the result
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 CODE, VALUE FROM DB1 WHERE CODE = #CODE", con)
cmd.Parameters.AddWithValue("#CODE", "2419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
value = reader.Read()
End Using
End Using
End Using
row.Cells(1) = value ' put it in the datagridview cell
Next
Fill it as the rows draw..
Protected Sub GridView1_RowDataBound(sender As Object, e As _
System.Web.UI.WebControls.GridViewRowEventArgs) Handles _
GridView1.RowDataBound
Dim DGRow As GridViewRow = sender
If DGRow.RowType = DataControlRowType.DataRow Then
Dim TestPath As String = DGRow.Cells(0).Text
Dim FoundKey As String = GetKeyFromOtherDatabase(TestPath)
DGRow.Cells(1).Text = FoundKey
End If
End Sub
Private Function GetKeyFromOtherDatabase(testpath) As String
Dim FoundKey As String = ""
' FoundKey = Double something magical...
Return FoundKey
End Function