How to create for each of the MS Access datatables in vb.net?. So I want to appear one by one according to "EMPID" in print preview. should appear in those print preview based on one row each
Private Sub Generate()
report.Clear()
Dim dt As New DataTable()
Dim query = "Select EMPID,[NAME],MONTHLYSALARY From tblemployee"
Using adapter As New OleDbDataAdapter(query, Con)
adapter.Fill(dt)
End Using
For Each row As DataRow In dt.Rows
Dim EMPID As String = row("EMPID").ToString()
Dim NAME As String = row("NAME").ToString()
Dim MONTHLYSALARY As String = row("MONTHLYSALARY").ToString()
report.AddDataTable(dt)
report.NewPage()
Next row
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Generate()
report.ShowPrintPreviewDialog()
End Sub
As I've said in the comments, this loop doesn't make sense as it is:
For Each row As DataRow In dt.Rows
Dim EMPID As String = row("EMPID").ToString()
Dim NAME As String = row("NAME").ToString()
Dim MONTHLYSALARY As String = row("MONTHLYSALARY").ToString()
report.AddDataTable(dt)
report.NewPage()
Next row
As it is, you loop through rows and get the field values from the current row and just ignore them, then add the whole table to the report. You add the whole table to the report multiple times, once for each row.
I don't use that reporting tool and there doesn't seem to be any proper documentation at present so I'll make an educated guess at what to do. Your first choice should be to use a method that allows you to add a single DataRow
, if one exists, e.g.
For Each row As DataRow In dt.Rows
report.AddDataRow(row)
report.NewPage()
Next row
If that's not possible, the next option should be a method that allows you to add a list of DataRows
, e.g.
For Each row As DataRow In dt.Rows
report.AddDataRows({row})
report.NewPage()
Next row
If that's not possible, you can stick with the method you're using to add a DataTable
but you need to create a new DataTable
for each row, not add the existing DataTable
, containing all the rows, multiple times, e.g.
For Each row As DataRow In dt.Rows
Dim table = {row}.CopyToDataTable()
report.AddDataTable(table)
report.NewPage()
Next row
EDIT:
Based on the screenshot that was added to the question of methods available, you might also use DataViews
of the original DataTable
instead of new DataTables
, e.g.
For Each row As DataRow In dt.Rows
Dim view = New DataView(dt, row(dt.PrimaryKey.First()), Nothing, DataViewRowState.CurrentRows)
report.AddDataView(view)
report.NewPage()
Next row
That assumes that the DataTable
has a PrimaryKey
and it is a single column. Presumably your EMPID
should be the PK. If it's not, try setting the MissingSchemaAction
property of your data adapter to AddWithKey
and the PK information should be propagated from the database.