How to add Header Columns to PDF Sql, Vb.net - sql

How to add Header Columns('ID, Name, Class, Date'. When I'm exporting to pdf from database pdf documnet not showing header columns how to add header columns to pdf. Thank you...
Dim table As New PdfPTable(5)
table.TotalWidth = 516.0F
table.LockedWidth = False
Dim widths As Single() = New Single() {1.0F, 2.0F, 3.0F, 4.0F, 5.0F}
table.SetWidths(widths)
table.HorizontalAlignment = 0
table.SpacingBefore = 20.0F
table.SpacingAfter = 20.0F
Dim connect As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\nagaraju\Documents\Attendance.mdf;Integrated Security=True;Connect Timeout=30"
Using conn As New SqlConnection(connect)
Dim pdfDoc As New Document()
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("C:\Users\nagaraju\Documents\pdf\" & TextBox1.Text & ".pdf", FileMode.Create))
pdfDoc.Open()
Dim img As Image = Image.GetInstance(My.Resources.Header, System.Drawing.Imaging.ImageFormat.Jpeg)
pdfDoc.Add(img)
img.ScalePercent(50.0F)
img.ScaleToFit(250.0F, 250.0F)
Dim query As String = "SELECT ID,Name,Class,Date,Intime FROM stuattrecordAMPM where ID=#ID and Date between #Date1-1 and #Date2"
Dim cmd As New SqlCommand(query, conn)
cmd.Parameters.Add("#ID", SqlDbType.Int)
cmd.Parameters("#ID").Value = TextBox1.Text
cmd.Parameters.Add("#Date1", SqlDbType.DateTime).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Date2", SqlDbType.DateTime).Value = DateTimePicker2.Value
Try
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
table.AddCell(rdr(0).ToString())
table.AddCell(rdr(1).ToString())
table.AddCell(rdr(2).ToString())
table.AddCell(rdr(3).ToString())
table.AddCell(rdr(4).ToString())
End While
End Using
Catch ex As Exception
End Try
pdfDoc.Add(table)
pdfDoc.Close()
End Using

Related

How to use WHERE condition to filter database table 'ID' vb.net

I wanted to filter database table using WHERE condition and save asper filter 'ID'
Database table:
ID
Name
Class
Date
1001
Todkar Sudhir S
1st
30-10-2022
1001
Todkar Sudhir S
1st
31-10-2022
1002
Sawant pooja B
2nd
30-10-2022
1002
Sawant pooja B
2nd
31-10-2022
This is my code which I tried to get result but I'm not understanding how to use where condition and how to save in iTextsharp pdf on 'ID'
Dim table As New PdfPTable(4)
table.TotalWidth = 416.0F
table.LockedWidth = False
Dim widths As Single() = New Single() {1.0F, 2.0F, 3.0F, 4.0F}
table.SetWidths(widths)
table.HorizontalAlignment = 0
table.SpacingBefore = 20.0F
table.SpacingAfter = 30.0F
Dim cell As New PdfPCell(New Phrase("Table Batch"))
cell.Colspan = 4
cell.Border = 0
cell.HorizontalAlignment = 1
table.AddCell(cell)
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim pdfDoc As New Document()
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("D:\pdf\" & DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") & ".pdf", FileMode.Create))
pdfDoc.Open()
Dim query As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Dim cmd As New SqlCommand(query, conn)
Try
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
table.AddCell(rdr(0).ToString())
table.AddCell(rdr(1).ToString())
table.AddCell(rdr(2).ToString())
table.AddCell(rdr(3).ToString())
End While
End Using
Catch ex As Exception
End Try
pdfDoc.Add(table)
pdfDoc.Close()
End Using
End Sub
Your code needs to use Add Method of sqlCommand parameters
Using conn As New SqlConnection(connect)
...
Dim query As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Dim cmd As New SqlCommand(query, conn)
cmd.Parameters.Add("#ID", SqlDbType.Int)
cmd.Parameters("#ID").Value = <ID e.x. 1001>
...
End Using
Visit this topic for more information:
SqlCommand.Parameters Property

sqlite read pdf file from database

I'm a little stuck with this...
I have a code to insert a PDF file into a blob as bytes:
Dim ofd As New OpenFileDialog
With ofd
.InitialDirectory = Application.StartupPath
.Filter = "PDF Files|*.pdf"
.FileName = Nothing
.ShowDialog()
End With
MsgBox(ofd.FileName)
Dim filePath As String = ofd.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
Dim con As New SQLiteConnection(db)
Dim cmd As New SQLiteCommand
Try
con.Open()
cmd = con.CreateCommand
cmd.CommandText = "UPDATE Employee SET File = #File WHERE ID = 20"
cmd.Parameters.Add("#File", SqlDbType.Binary).Value = bytes
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
cmd.Dispose()
End Try
This works, but now I need to reverse it and load the PDF file (I don't want to save the PDF back into the computer, all I need is to view it...)
This is what I have to retrieve the PDF file:
Dim con As New SQLiteConnection(db)
Dim cmd As New SQLiteCommand
Dim File As New DataTable
Try
con.Open()
cmd = con.CreateCommand
Dim CommandText As String = "SELECT File FROM Employee WHERE ID = 20"
Dim adapter As New SQLiteDataAdapter(CommandText, con)
adapter.Fill(File)
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
cmd.Dispose()
End Try
But it doesn't work...
Anyone have another way to do it?
So this is how I fixed it...
Try
con.Open()
cmd = con.CreateCommand
cmd.CommandText = "SELECT File FROM Employee WHERE ID = 20"
Dim bytes As Byte() = cmd.ExecuteScalar()
Dim fs As FileStream = New FileStream("d:\test.pdf", FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
fs.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
cmd.Dispose()
End Try
Thanks for the help

i want to use transaction with my code in VB.NET

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.

Save and Update from Datagridview to Access Database

i've been fumbling with this problem for a while now. am trying to update/insert into my access database data from a datagridview on a form.
i've a maskedtextbox that i've masked to suit my primary key. when the mask is completed then automatically, records are read from the database to the textboxes and datagridview as shown in the attached picture.
i did that with this code
If STHN_ID.MaskCompleted = True Then
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
'da = New OleDbDataAdapter("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn) 'Change items to your database name
'da.Fill(ds)
'Dim view As New DataView(tables(0))
'source1.DataSource = view
'DependantView.DataSource = view
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
'connection.Open()
Dim myTable As DataTable = New DataTable
adapter.Fill(myTable)
DependantView.DataSource = myTable
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
my headache now is to update/insert into the database when records are added/edited in the datagridview based on the STHN_ID entered in the maskedtextbox. any help would be really appreciated.
sample
this is how i got it done!
on maskedtextbox with mask completed this is the code to read from database and load datagridview ...........
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
con = New OleDbConnection
con.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\PRINCE\Documents\STHNDatabase.accdb")
con.Open()
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
Dim connection As New OleDbConnection
connection.ConnectionString = connString
adapt = New OleDbDataAdapter("Select [DependentID],[DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship],[STHN_ID] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", con)
ds = New DataSet
adapt.Fill(ds, "DependantData")
DependantView.DataSource = ds.Tables(0)
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
and on the SaveButton Click this is the code.....
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
Try
builder = New OleDbCommandBuilder(adapt)
adapt.Update(ds, "DependantData")
MsgBox("Updated Successfully")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
thanks once again. really appreciate it

Error: No data exists for the row/column

I get the following error: No data exists for the row/column.
It should retrieve the image
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
dr.Close()
sSql = "select Pfile from Faculty where StId = '" & lab1id.Text & "'"
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader()
pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
pdr.Close()
The dr.GetValue(N) is zero-based ordinal. Change your indices:
While dr.Read()
lab1id.Text = dr.GetValue(0).ToString
lab1fname.Text = dr.GetValue(1).ToString
lab1lname.Text = dr.GetValue(2).ToString
lab1position.Text = dr.GetValue(3).ToString
lab1subject.Text = dr.GetValue(4).ToString
End While
While pdr.Read() ' | you got a typo here. Change `dr` to `pdr`.
Dim bits As Byte() = CType(pdr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
Consider changing your code to something like this:
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC;"
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
lab1id.Text = reader.Item("id").ToString
lab1fname.Text = reader.Item("fname").ToString
lab1lname.Text = reader.Item("lname").ToString
lab1position.Text = reader.Item("position").ToString
lab1subject.Text = reader.Item("subject").ToString
End While
End Using
End Using
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "select Pfile from Faculty where StId = #StId;"
command.Parameters.AddWithValue("#StId", lab1id.Text)
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
Dim bits As Byte() = CType(reader.Item("Pfile"), Byte())
Using stream As New MemoryStream(bits)
imgRetrieve.Image = Bitmap.FromStream(stream)
End Using
End While
End Using
End Using
The problem is you never execute pcmd, see the following two lines:
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader() ' cmd should be replaced with pcmd
I would suggest adding While...End While Statement when getting the values from dr and pdr. You also need to parameterize the second query to avoid SQL Injection.
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
End While
dr.Close()
sSql = "select Pfile from Faculty where StId = #StId"
Dim pcmd As New OleDbCommand(sSql, con)
pcmd.Parameters.AddWithValue("#StId", lab1id.Text)
Dim pdr As OleDbDataReader = pcmd.ExecuteReader()
While pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
pdr.Close()