I'm trying to fetch all the data rows in a sql server to print all the values. Here is the code I already tried but it still does not work. Can someone tell me what is wrong here? I'm quite new to vb.net
For i = 1 To 100
Dim testsection As String = e.Item.DataItem("sectionName")
e.Item.Cells(4).Text = strSection & testsection
Next
i dont quite understand how it fetch the data. i juz work as a fresh grad. but they already assign me this advance task. here is the codes in my DBFunction.
Public Function GetUserList(ByVal strUserLogin As String, ByVal strName As String, _
ByVal intCompanyID As Integer, ByVal tblName As String) As DataSet
Dim oConn As SqlConnection = Nothing
Dim SQLStr As String = ""
Dim SubSQL As String = ""
Dim CMD As SqlCommand = Nothing
Dim DS As New DataSet
Dim DA As New SqlDataAdapter
Try
oConn = New SqlConnection(ConnectionString)
oConn.ConnectionString = ConnectionString
oConn.Open()
CMD = oConn.CreateCommand
CMD.CommandType = CommandType.StoredProcedure
SQLStr = "sp_tblUser_Get"
'CMD.Parameters.Add("#CompanyID", SqlDbType.Int).Value = intCompanyID
CMD.Parameters.Add("#LoginID", SqlDbType.VarChar, 50).Value = strUserLogin
CMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = strName
'If strUserLogin <> "" Then
' SubSQL = " AND u.UserLogin = " & SQLS(strUserLogin)
'End If
'If intCompanyID <> 0 Then
' SubSQL = " AND u.CompanyId = " & SQLN(intCompanyID)
'End If
'SQLStr = "select u.ID, u.UserLogin, u.Name, c.CompanyName, u.CreateDate from tblUser u " & _
' " inner join tblCompany c on u.CompanyId = c.ID WHERE u.ID <> 0 " & SubSQL
CMD.CommandText = SQLStr
DA.SelectCommand = CMD
DA.Fill(DS, tblName)
CMD = Nothing
DA = Nothing
oConn.Close()
oConn = Nothing
Catch ex As System.Exception
DS = Nothing
Finally
If Not oConn Is Nothing Then
oConn.Close()
oConn = Nothing
End If
If Not CMD Is Nothing Then
CMD = Nothing
End If
End Try
Return DS
End Function
Basically lines from Dim oConn As SqlConnection = Nothing to DA.SelectCommand = CMD are used to create connection with the database and have steps to call procedure having name sp_tblUser_Get.
Then all the required parameters of this procedure are paased using lines
CMD.Parameters.Add("#LoginID", SqlDbType.VarChar, 50).Value = strUserLogin
CMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = strName
After that using SqlDataAdapter's Fill method data set is filled with the out put.
Dataset DS can contain single DataTable or multiple Datatables which depends on hot Stored procedure is written.
I am assuming it contains single datatable, then if you want to view data then in you can use.
DataTable dt= DS.Tables[0];
This dt Datatablw will contain all data.
To display that data you can use loop like mentioned below.
DataTable dt = DS.Tables[0];
foreach (DataRow dr in dt.Rows)
{
String Name = dr["FirstName"].ToString();
int Age = Convert.ToInt32(dr["Age"]);
}
Related
I have a table that has columns CustomerCell and ReceiptType. I need to create a SELECT statement that displays every record that matches CustomerCell or ReceiptType.
I tried this code:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = '" & TextBox1.Text & "') or ([RcptType] = 'Cash') "
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
End If
Where Textbox1 is for CustomerCell and CheckBox4 is for ReceiptType. When I enter customer cell and receipt type I should see 2 records however with the above code I can see only one record.
This is my form:
As stated, look into parameters to avoid SQL injection and it does clear up your query a little more. I've put this together which may help. Might need a few tweaks for your application:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim dt As DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = #RcptCustCell) or ([RcptType] = 'Cash') "
Using con As New SqlConnection(constr),
com As New SqlCommand(sqlstr, con)
com.Parameters.Add("#RcptCustCell", SqlDbType.VarChar).Value = TextBox1.Text
con.Open()
dt = New DataTable
dt.Load(com.ExecuteReader)
dgv.DataSource = dt
Call griddraw()
End Using
End If
Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt]"
If TextBox1.Text.trim.length <> 0 then
sqlstr += "where (RcptCustCell = '" & TextBox1.Text & "')"
endif
If chkPaymentCheck.checked then
if sqlstr.contains("where") = false then
sqlstr += "where RcptType = 'Check'"
EndIf
sqlstr += "or RcptType = 'Check'"
endif
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
Try this and you can continue with the if statements to add more checks.
I am using SqlDataAdapter and SqlCommandBuilder to insert and update, and I want to use transaction to insert into two tables with this way but I have tried a lot and I didn't succeed
thanks
Dim sql = "select * from ReceiptOfItems where receiptCode=N'" & receiptCode.Text & "' "
Dim dta As New SqlClient.SqlDataAdapter(sql, con)
Dim ds As New DataSet
dta.Fill(ds)
Dim dt As DataTable
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
' MsgBox("اسم االتصنيفل او رقمه موجود مسبقا ", MsgBoxStyle.Exclamation, "رسالة تنبيه")
receiptCode.Text = Format(Val(GetLastRecord("ReceiptOfItems", "receiptcode")) + 1, "REC0000000")
End If
Dim dr = dt.NewRow
dr!receiptCode = receiptCode.Text
dr!receiptDate = Format(receiptDate.Value, "yyyy/MM/dd")
' dr!receiptDate = receiptDate.Text
dr!supplierCode = GetsupplierCode(supplierName.Text)
dr!SupplierInvoiceCode = SupplierInvoiceCode.Text
dr!supplierInvoiceDate = Format(supplierInvoiceDate.Value, "yyyy/MM/dd")
'dr!supplierInvoiceDate = supplierInvoiceDate.Text
dr!TotalDiscount = Val(TotalDiscount.Text)
dr!TotalReceipt = Val(TotalReceipt.Text)
dr!TotalArabic = TotalArabic.Text
dr!SupplierInvoiceType = SupplierInvoiceType.Text
dr!salesTax = Val(salesTax.Text)
dr!note = note.Text
dr!status = True
dt.Rows.Add(dr)
Dim cmd As New SqlCommandBuilder(dta)
This should work for you:
con.Open()
Dim trans As SqlTransaction = con.BeginTransaction()
Try
Dim insertStr As String = "insert into ReceiptOfItems (receiptCode, receiptDate, etc.) values(#receiptCode, #receiptDate, #etc)"
Dim insertCmd As New SqlCommand(insertStr, con, trans)
For Each dc As DataColumn In dt.Columns
Dim param As New SqlParameter()
param.ParameterName = dc.ColumnName
param.SourceColumn = dc.ColumnName
insertCmd.Parameters.Add(param)
Next
dta.InsertCommand = insertCmd
dta.Update(ds)
trans.Commit()
con.Close()
Catch ex As Exception
trans.Rollback()
End Try
The DataAdapter class has an UpdateCommand and a DeleteCommand property which must be built appropriately if you are doing something other than inserting new rows.
Dim connstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\vladut.moraru\Desktop\TCO Orders\02_Template_BOM.xls;Extended Properties=""Excel 8.0;HDR=YES;"""
Dim pram As OleDbParameter
Dim dr As DataRow
Dim olecon As OleDbConnection
Dim olecomm As OleDbCommand
Dim olecomm1 As OleDbCommand
Dim oleadpt As OleDbDataAdapter
Dim ds As DataSet
Try
olecon = New OleDbConnection
olecon.ConnectionString = connstring
olecomm = New OleDbCommand
olecomm.CommandText = "Select Level, F_N, Name, Rev from [BOM$]"
olecomm.Connection = olecon
olecomm1 = New OleDbCommand
olecomm1.CommandText = "Insert into [BOM$] " & "(Level, F_N, Name, Rev) values " & "(#FName, #LName, #Age, #Phone)"
olecomm1.Connection = olecon
pram = olecomm1.Parameters.Add("#FName", OleDbType.VarChar)
pram.SourceColumn = "Level"
pram = olecomm1.Parameters.Add("#LName", OleDbType.VarChar)
pram.SourceColumn = "F_N"
pram = olecomm1.Parameters.Add("#Age", OleDbType.VarChar)
pram.SourceColumn = "Name"
pram = olecomm1.Parameters.Add("#Phone", OleDbType.VarChar)
pram.SourceColumn = "Rev"
oleadpt = New OleDbDataAdapter(olecomm)
ds = New DataSet
olecon.Open()
oleadpt.Fill(ds, "BOM")
If IsNothing(ds) = False Then
dr = ds.Tables(0).NewRow
dr("Level") = "Raman"
dr("F_N") = "Tayal"
dr("Name") = 24
dr("Rev") = 98989898
ds.Tables(0).Rows.Add(dr)
oleadpt = New OleDbDataAdapter
oleadpt.InsertCommand = olecomm1
Dim i As Integer = oleadpt.Update(ds, "BOM")
End If
Catch ex As Exception
Finally
olecon.Close()
olecon = Nothing
olecomm = Nothing
oleadpt = Nothing
ds = Nothing
dr = Nothing
pram = Nothing
End Try
I want tot write into tamplate excel with column Level, F_N, Name, Rev and my code generate that error from title. I want to insert some value in my excel but on line oleadpt.Fill(ds, "BOM") give me that error. I put a pic with excel file. The sheet name is BOM
My question is, where i miss to generate that code? I write wrong my columns or my connection?
I am retrieving records from a database with the following code.
Dim SearchID As Integer = teacherID
Dim NewStudentID As Integer = studentID
Dim DisplayTable As New DataTable()
Dim da As New OleDbDataAdapter()
Dim sqlquery As String = ("select * from tblAppointments WHERE TeacherID =" & teacherID & "")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
da.SelectCommand = New OleDbCommand(sqlquery, conn)
da.Fill(Finalds, "Display")
DisplayTable = Finalds.Tables("Display")
DisplayTable.Columns.Remove("Instrument")
DisplayTable.Columns.Remove("Room")
DisplayTable.Columns.Remove("TeacherID")
Registersgridview.DataSource = DisplayTable
Registersgridview.Columns(0).Visible = False
conn.Close()
Catch ex As Exception
MsgBox("There are no appointments in the database for " + Tutorcombox.Text)
End Try
It also there then added to a datagridview and certain columns are removed and some are hidden aswell.
Because its essentially a register, when the use clicks on the datagridview field that is a boolean it changes from false to true. I have been trying to send this back to the database, but have had no luck. I have tried the following :
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next
But have had no luck with doing so, as it crashes without an error.
Can anyone help?
I solved the problem myself, if any of you are having similar problems here is the solution
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
Dim appID As Integer = Registersgridview.Rows(i).Cells(0).Value
Dim present As Boolean = Registersgridview.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("appID") = appID
row.Item("Present") = present
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "UPDATE tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.Connection = conn
.ExecuteNonQuery()
End With
Next
conn.Close()
Registersgridview.DataSource = Nothing
dt.Clear()
try this:
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(5))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next
I have a code that will fill the dataset for my crystal report which was written down as follows:
Dim str1 As String = "SELECT * FROM farm_loan WHERE id = '" & txtAgreement.Text & "'"
Dim str2 As String = "SELECT * FROM cd_farmers WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str3 As String = "SELECT * FROM cd_Address WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str4 As String = "SELECT * FROM cd_loan_charges WHERE loanid = '" & txtAgreement.Text & "'"
Dim ad1 As SqlDataAdapter = New SqlDataAdapter(str1, Conn)
Dim ad2 As SqlDataAdapter = New SqlDataAdapter(str2, Conn)
Dim ad3 As SqlDataAdapter = New SqlDataAdapter(str3, Conn)
Dim ad4 As SqlDataAdapter = New SqlDataAdapter(str4, Conn)
Dim LDPSDataSet As DataSet = New DataSet()
ad1.Fill(LDPSDataSet, "farm_loan")
ad2.Fill(LDPSDataSet, "cd_farmers")
ad3.Fill(LDPSDataSet, "cd_Address")
ad4.Fill(LDPSDataSet, "cd_loan_charges")
The above code works fine. What I am trying to do is to store the sql statement in one table called tblDataSet and load the same from sql server. Here are my code.
cmd = New SqlCommand("SELECT * FROM tblDataSet WHERE Flag = 'Y'", Conn)
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim ad As SqlDataAdapter
If reader.HasRows Then
Do While reader.Read()
MySql = reader(1).ToString
Dim table As String = reader(2).ToString
Dim comm As SqlCommand = New SqlCommand(MySql)
comm.Connection = Conn
comm.CommandType = CommandType.Text
comm.Parameters.Add("#AgreementID", SqlDbType.Int).Value=txtAgreement.Text
comm.Parameters.Add("#CustomerID", SqlDbType.Int).Value = txtCustID.Text
Dim ad As SqlDataAdapter = New SqlDataAdapter
For Each tbl As DataTable In LDPSDataSet.Tables()
If tbl.TableName = table Then
ad.SelectCommand = comm
End If
Exit For
ad.Update(tbl)
Next
Loop
End If
I have not encountered any error but no value is fetch to the crystal report.
My code in to fetch data to crystal report is show below.
With mReport
repOptions = .PrintOptions
With repOptions
.PaperOrientation = rptOrientation
.PaperSize = rptSize
.PrinterName = printer
End With
.Load(rptPath, OpenReportMethod.OpenReportByDefault)
.SetDataSource(LDPSDataSet)
'.Refresh()
.PrintToPrinter(1, True, 0, 0)
End With
Please help me identify the problem with my code.
Thanks in advance.