How to using Linq with Dataview? - vb.net

I am learning linq to dataset from this post: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/creating-a-dataview-object-linq-to-dataset
and I am having trouble when running this code, I do not understand why it doesn't work, however
The code works fine if I delete this line:
Where order1.Field(Of Integer)("Column2") = 1
my table have 4 columns corresponds to the name: Column1,2,3,4
Here is vbcode:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet = New System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source='C:\Users\Username\Downloads\Danh STT.xlsx';Extended Properties='Excel 12.0 Xml;HDR=YES;'")
MyCommand = New System.Data.OleDb.OleDbDataAdapter _
("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Author", "TestTable")
MyCommand.Fill(DtSet)
Dim orders As DataTable = DtSet.Tables(0)
Dim query = From order1 In orders.AsEnumerable
Order By order1.Field(Of String)("Column1")
Where order1.Field(Of Integer)("Column2") = 1
Select order1
Dim view As System.Data.DataView = New Data.DataView
view = query.AsDataView()
DataGridView1.DataSource = view
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Can you explain for me please!
Thanks a lot.
Edit: [The error I received]
{System.InvalidCastException: Specified cast is not valid." & vbCrLf & " at System.Data.DataRowExtensions.UnboxT1.ValueField(Object value)" & vbCrLf & " at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)" & vbCrLf & " at Dataview.Form1._Closure$__._Lambda$__1-0(DataRow order1) in D:\2.0_VSTO_PROJECT\D_1_MY_PROJECT\1 EXCEL\.NET\1 Class .Net\LinqExample\Dataview\Dataview\Form1.vb:line 31" & vbCrLf & " at System.Data.EnumerableRowCollection1.b__16_0(DataRow row)" & vbCrLf & " at System.Data.EnumerableRowCollection1.<>c__DisplayClass16_0.<GetLinqDataView>b__3(DataRow row)" & vbCrLf & " at System.Data.DataView.RowPredicateFilter.System.Data.IFilter.Invoke(DataRow row, DataRowVersion version)" & vbCrLf & " at System.Data.Index.AcceptRecord(Int32 record, IFilter filter)" & vbCrLf & " at System.Data.Index.InitRecords(IFilter filter)" & vbCrLf & " at System.Data.Index..ctor(DataTable table, IndexField[] indexFields, Comparison1 comparison, DataViewRowState recordStates, IFilter rowFilter)" & vbCrLf & " at System.Data.DataView.UpdateIndex(Boolean force, Boolean fireEvent)" & vbCrLf & " at System.Data.DataView.UpdateIndex(Boolean force)" & vbCrLf & " at System.Data.DataView.SetIndex2(String newSort, DataViewRowState newRowStates, IFilter newRowFilter, Boolean fireEvent)" & vbCrLf & " at System.Data.DataView..ctor(DataTable table, Predicate1 predicate, Comparison1 comparison, DataViewRowState RowState)" & vbCrLf & " at System.Data.EnumerableRowCollection1.GetLinqDataView()" & vbCrLf & " at System.Data.DataTableExtensions.AsDataView[T](EnumerableRowCollection1 source)" & vbCrLf & " at Dataview.Form1.Button1_Click(Object sender, EventArgs e) in D:\2.0_VSTO_PROJECT\D_1_MY_PROJECT\1 EXCEL.NET\1 Class .Net\LinqExample\Dataview\Dataview\Form1.vb:line 36}

Related

Select records from ms access table using query with two date conditions and another

I am using a select statement to retrieve records from an ms access table between two dates and another condition to check for customers name
I get the error "No value given for one or more required parameters"
The code is as below
Try
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
Dim dtDate1 As DateTime = DateTime.Parse(dtpDateFrom.Text)
Dim dtDate2 As DateTime = DateTime.Parse(dtpDateTo.Text)
''''SQL_PaymentsP = "SELECT InvoiceID,CustomerName,InvoiceDate,InvoiceAmount,PaymentDesc,PaidAmount,DatePaid,CurrentBalance FROM Payments WHERE [DatePaid] BETWEEN #" & dtDate1.ToString("MM/dd/yyyy") & "# AND #" & dtDate2.ToString("MM/dd/yyyy") & "# " & "OR [CustomerName] = " & txtCustomer.Text & ""
SQL_PaymentsP = "SELECT Payments.PaymentID, Payments.InvoiceID, Payments.CustomerName, Payments.InvoiceDate, Payments.InvoiceAmount, Payments.PaymentDesc, Payments.PaidAmount, Payments.DatePaid, Payments.CurrentBalance, Payments.Status FROM Payments WHERE Payments.DatePaid Between #" & dtDate1.ToString("MM/dd/yyyy") & "# And #" & dtDate2.ToString("MM/dd/yyyy") & "# " & " OR " & "Payments.CustomerName =" & txtCustomer.Text & ""
' SQLInvoicesP = "Select DateInvoice,IDInvoices,InvoiceAmount,CustomerName,Mode from Invoices where DateInvoice between #" & dtDate1.ToString("MM/dd/yyyy") & "# and #" & dtDate2.ToString("MM/dd/yyyy") & "#"
DataSet_PaymentsP.Clear()
Dim DataAdapter_PaymentsP As New OleDbDataAdapter(SQL_PaymentsP, Conn)
DataAdapter_PaymentsP.Fill(DataSet_PaymentsP, "Payments")
Conn.Close()
Application.DoEvents()
Dim ConInfo As New CrystalDecisions.Shared.TableLogOnInfo
ConInfo.ConnectionInfo.ServerName = Application.StartupPath & "\DB.mdb"
ConInfo.ConnectionInfo.DatabaseName = "kuku.mdb"
ConInfo.ConnectionInfo.UserID = "Admin"
ConInfo.ConnectionInfo.Password = ""
Dim rpt1 As New CrystalReport5
rpt1.Database.Tables(0).ApplyLogOnInfo(ConInfo)
rpt1.SetDataSource(DataSet_PaymentsP)
rpt1.SetParameterValue("Start_Date", dtDate1)
rpt1.SetParameterValue("End_Date", dtDate2)
rpt1.SetParameterValue("CustomerName", txtCustomer.Text)
rpt1.SetParameterValue("Author", FormMain.XN.Text)
Dim frm As New FormPrint
frm.CrystalReportViewer1.ReportSource = rpt1
frm.CrystalReportViewer1.LogOnInfo(0).ConnectionInfo.Password = "yazsys.com1234"
frm.ShowDialog()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
I just did add the single quotation marks as shown below and the select query can now retrieve records fro ms access
SQL_PaymentsP = "SELECT Payments.PaymentID, Payments.InvoiceID,
Payments.CustomerName, Payments.InvoiceDate, Payments.InvoiceAmount,
Payments.PaymentDesc, Payments.PaidAmount, Payments.DatePaid, Payments.CurrentBalance, Payments.Status FROM Payments WHERE Payments.DatePaid Between '#" & dtDate1.ToString("MM/dd/yyyy") & "#' And '#" & dtDate2.ToString("MM/dd/yyyy") & "#' OR " & "Payments.CustomerName ='" & txtCustomer.Text & "'"

Fetch output of DBMS_OUTPUT.PUT_LINE in a VB .net application

I am trying to get a simple hello world output in vb from a pl/sql anonymous block
As far as I tried
Imports System.Data
Imports Oracle.DataAccess.Client
Imports Oracle.DataAccess.Types
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim oradb As String = "Data Source=(DESCRIPTION=" _
+ "(ADDRESS=(PROTOCOL=TCP)(HOST=vmDA2D319)(PORT=1521))" _
+ "(CONNECT_DATA=(SERVICE_NAME=XE)));" _
+ "User Id=hr;Password=hr;"
Dim conn As New OracleConnection(oradb)
conn.Open()
Dim cmd As New OracleCommand
cmd.Connection = conn
cmd.CommandText = "set server output on;" & vbNewLine & "DECLARE" & vbNewLine & "message varchar2(20):= 'Hello, World!'; " & vbNewLine & "BEGIN()" & vbNewLine & "dbms_output.put_line(message);" & vbNewLine & "END;" & vbNewLine & "/"
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
dr.Read()
Label1.Text = dr.ExecuteReader
conn.Dispose()
End Sub
End Class
Now this is the Part where I am stuck now. I just want fetch the output in a textbox actually.
But I am just trying to get the output in a label or maybe in a messagebox first.
UPDATE
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim oradb As String = "Data Source=(DESCRIPTION=" _
+ "(ADDRESS=(PROTOCOL=TCP)(HOST=vmDA2D319)(PORT=1521))" _
+ "(CONNECT_DATA=(SERVICE_NAME=XE)));" _
+ "User Id=hr;Password=hr;"
Dim conn As New OracleConnection(oradb)
conn.Open()
Dim cmd As New OracleCommand
cmd.CommandText = "set server output on;" & vbNewLine & "DECLARE" & vbNewLine & "return_value VARCHAR2(100) := 'Hello World!';" & vbNewLine & "get_status INTEGER;" & vbNewLine & "BEGIN" & vbNewLine & "DBMS_OUTPUT.GET_LINE (return_value, get_status);" & vbNewLine & "IF get_status = 0" & vbNewLine & "THEN" & vbNewLine & "RETURN return_value;" & vbNewLine & "ELSE" & vbNewLine & "RETURN NULL;" & vbNewLine & "END IF;" & vbNewLine & "END;" & vbNewLine & "/"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("return_value", OracleDbType.Varchar2, 100)
cmd.Parameters("return_value").Direction = ParameterDirection.Output
cmd.Connection = conn
cmd.ExecuteScalar()
Label1.Text = cmd.Parameters("return_value").Value
conn.Dispose()
End Sub
I am getting error at cmd.ExecuteScalar()
with ORA-00922: missing or invalid option

Insert multiple records to database using MS Access 2007

I'm using Visual Basic (VB 2010).
How do I insert multiple records to the database using MS Access 2007? My code is not working:
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
If DataGridView1.Rows(0).Cells(0).Value = "" Then
MsgBox("Belum ada transaksi", MsgBoxStyle.Exclamation, "Informasi")
Exit Sub
End If
If TextBox6.Text = "" Then
MsgBox("Jumlah bayar belum diinput!", MsgBoxStyle.Exclamation, "Informasi")
Exit Sub
End If
On Error Resume Next
If RadioButton1.Checked Then
For baris As Integer = 0 To DataGridView1.Rows.Count - 2
Dim simpan As String = "Insert into TBL_JUALTUNAI (NomorFaktur,TglTransaksi,WaktuTransaksi,KodeBarang,NamaBarang,HargaSatuan,JumlahBeli,Total) values " & _
"('" & TextBox10.Text & "','" & TextBox11.Text & "','" & TextBox12.Text & "','" & DataGridView1.Rows(0).Cells(0).Value & "','" & DataGridView1.Rows(0).Cells(1).Value & "','" & DataGridView1.Rows(0).Cells(2).Value & "','" & DataGridView1.Rows(0).Cells(3).Value & "','" & DataGridView1.Rows(0).Cells(4).Value & "')"
CMD = New OleDbCommand(simpan, CONN)
CMD.ExecuteNonQuery()
Next baris
End If
If RadioButton2.Checked Then
Dim simpan1 As String = "Insert into TBL_PELANGGAN (NomorFaktur,TglTransaksi,WaktuTransaksi,NamaPelanggan,AlamatPelanggan,TelpPelanggan,KodeBarang,NamaBarang,HargaSatuan,JumlahBeli,Total) values " & _
"('" & TextBox10.Text & "','" & TextBox11.Text & "','" & TextBox12.Text & "','" & DataGridView1.Rows(0).Cells(7).Value & "','" & DataGridView1.Rows(0).Cells(8).Value & "','" & DataGridView1.Rows(0).Cells(9).Value & "','" & DataGridView1.Rows(0).Cells(0).Value & "','" & DataGridView1.Rows(0).Cells(1).Value & "','" & DataGridView1.Rows(0).Cells(2).Value & "','" & DataGridView1.Rows(0).Cells(3).Value & "','" & DataGridView1.Rows(0).Cells(4).Value & "')"
CMD = New OleDbCommand(simpan1, CONN)
CMD.ExecuteNonQuery()
End If
CMD = New OleDbCommand("select * from TBL_BARANG where KodeBarang='" & DataGridView1.Rows(0).Cells(0).Value & "'", CONN)
RD = CMD.ExecuteReader
RD.Read()
If RD.HasRows Then
Dim kurangistok As String = "update TBL_BARANG set StockBarang= '" & RD.Item(4) - DataGridView1.Rows(0).Cells(3).Value & "' where KodeBarang='" & DataGridView1.Rows(0).Cells(0).Value & "'"
CMD = New OleDbCommand(kurangistok, CONN)
CMD.ExecuteNonQuery()
End If
End Sub
End Class
With that code, you aren't going to insert multiple records at once. Each INSERT command will only insert one row, so you have to use multiple INSERT commands for multiple rows.
If I'm understanding you correctly, you have a DataGridView where there multiple rows, and you want to insert the selected rows, yes?
Correct me if I'm wrong, but what you should be doing is enumerating through the DataGridView's rows and insert a row to the database for each row in that DataGridView?
In that case, use a For Each loop to retrieve the rows (DataGridView1.Rows) and then execute your INSERT command in that loop.
Edit: In reply to your comment, I don't know the full context of your code, but I can get you started.
For Each dgvRow As DataGridViewRow In dgv.Rows
Dim myCommand As String = "INSERT INTO " 'From here, insert your parameters for that row. You can call on dgvRow.Cells.
CMD = New OleDbCommand(myCommand, CONN)
CMD.ExecuteNonQuery()
Next

syntax error insert into statement vb.net

pls help solve me this question.. im very new to this
i can't add new employee to the table employee.. whenever i try to add it shows syntax error insert into statement
Public Class AddNewEmployee
Dim dr As OleDbDataReader
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim conn As New OleDbConnection(My.Settings.rayshadatabaseConnectionString)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn.Open()
Try
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
cmd = New OleDbCommand(str, conn)
Dim i As Integer = cmd.ExecuteNonQuery()
If i > 0 Then
MessageBox.Show("Record Succesfully added.", "Process Completed", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Adding failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Close()
cmd.Dispose()
End Try
frmEmployee.loadR()
Me.Close()
End Sub
End Class
Replace this,
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
with this,
Dim str As String = "INSERT INTO employee" _
& "([Employee Name], [IC Number], [HP Number], [Address])" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
Thanks
Manoj

The CommandText property has not been properly initialized

i am using vb.net and mysqladmin as my database.
i have a problem in my codes, and i don't know how to debug it.
please help me..
my problem is when i click the button update the error shows
"The CommandText property has not been properly initialized."
this is the codes:
Dim intDB_ID_Selected As Integer
'Private Sub cmdupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdupdate.Click
If MessageBox.Show("Do you want to update this record?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
Dim sqlcommand As New MySqlCommand("UPDATE user_info " & _
" SET name = '" & txtname.Text.Trim & "'," & _
" address = '" & txtaddress.Text.Trim & "', " & _
" age = '" & txtage.Text.Trim & "', " & _
" WHERE id= '" & intDB_ID_Selected & "'", sConnection)
Call execCmd(SQL)
load1()
MsgBox("Record updated successfully.", MsgBoxStyle.Information)
End If
End Sub `
Public Sub execCmd(ByVal PstrSQL As String)
With cmd
.CommandText = PstrSQL
.ExecuteNonQuery()
End With
End Sub
the error line is in
.ExecuteNonQuery()
i am a beginner in this language, so please help me. im begging you guys!!
what is cmd and has it been initialized?
Oh, and try to used parameterized query. The earlier you get into the habit, the better.
Try doing this instead after the messagebox selection. cmd is not properly initialized in execCmd.
Dim sqlStr as String = "UPDATE user_info " & _
" SET name = '" & txtname.Text.Trim & "'," & _
" address = '" & txtaddress.Text.Trim & "', " & _
" age = '" & txtage.Text.Trim & "', " & _
" WHERE id= '" & intDB_ID_Selected & "'", sConnection)
Dim sqlcommand As New MySqlCommand(sqlStr)
sqlcommand.ExecuteNonQuery()
load1()
MsgBox("Record updated successfully.", MsgBoxStyle.Information)