Print Parameter in Report - vb.net

This is my VB.NET (2012) code to show report based on Combobox (cmbCustomer) selection, I want to print that parameter cmbCustomer.text on report.
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Me.rpt_customerByDateTableAdapter.Fill(Me.customerByDateDataSet.rpt_customerByDate,
cmbCustomer.Text)
Me.ReportViewer1.RefreshReport()
End Sub

Here's how, assuming you have already created a parameter in your rldc
Dim customer As String = cmbCustomer.text
Dim CustomerParam As New ReportParameter("yourCustomerParameter", customer)
Dim reportParameters() As ReportParameter = {CustomerParam}
Me.DataTable1TableAdapter.Fill(Me.customerByDateDataSet.rpt_customerByDate,
cmbCustomer.Text)
Me.ReportViewer1.LocalReport.SetParameters(reportParameters)
Me.ReportViewer1.RefreshReport()

Related

DataTable to Crystal Report

I'm trying to print the conents of DataGrid into CrystalReport by passing data from DGV to Datatable then to Crystal Report, it works but my problem is it only displays the first row in the crystal report... I need all the rows to be printed.. here's the code below:
'
Dim dt_RadLogBook As New DataTable("dt_RadLogBook")
With dt_RadLogBook
.Columns.Add("CaseNumber")
.Columns.Add("Name")
.Columns.Add("BirthDate")
.Columns.Add("PhilHealth Membership")
.Columns.Add("Ward Name")
.Columns.Add("Address")
.Columns.Add("LMP")
End With
For Each dgr As DataGridViewRow In frmRadLogBook.dgvLogBook.Rows
dt_RadLogBook.Rows.Add(dgr.Cells(0).Value, dgr.Cells(1).Value, dgr.Cells(2).Value, dgr.Cells(3).Value, dgr.Cells(4).Value, dgr.Cells(5).Value, dgr.Cells(6).Value)
MsgBox(dgr.Cells(0).ToString)
Next
Dim rptDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument
rptDocument = New rptRadLogBook1
rptDocument.SetDataSource(dt_RadLogBook)
frmReportForm.CRV1.ReportSource = rptDocument
frmReportForm.ShowDialog()
'
Instead of re-inventing the wheel, you can extract the DataSource from the DataGridView.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click
Dim dt = DirectCast(frmRadLogBook.dgvLogBook.DataSource, DataTable)
Dim rptDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument
rptDocument = New rptRadLogBook1
rptDocument.SetDataSource(dt)
frmReportForm.CRV1.ReportSource = rptDocument
frmReportForm.ShowDialog()
End Sub
I don't have Crystal Reports so I can not test the rest of the code.

ifselectedindex changed , show data in a textbox

I've linked an access database to my form.
I have 1 table , 2 rows
1 = Researchtype short text
2 = Researchdetails (long text)
In my combobox1 i've binded my researchtype row so i can choose a type of research.
Question now: how can i bind the details data to the richtextbox below it in order to show the research data as soon as i choose a research type?
I've tried if else combos, try catch combos,
i'm thinking i'm actually overthinking the issue here.
What would be the easiest way to "select from dropdown" and show the result in textbox.
I'm a vb.net beginner
Public Class Onderzoeken
Private Sub Onderzoeken_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PatientenDatabaseDataSetX.tbl_OnderzoeksTypes' table. You can move, or remove it, as needed.
Me.Tbl_OnderzoeksTypesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_OnderzoeksTypes)
End Sub
Private Sub cboxOnderzoek_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboxOnderzoek.SelectedIndexChanged
If cboxOnderzoek.SelectedItem = Nothing Then
cboxOnderzoek.Text = ""
Else
rtbBeschrijvingOnderzoek.Text = CStr(CType(cboxOnderzoek.SelectedItem, DataRowView)("OZ_Onderzoeksbeschrijving"))
End If
End Sub
End Class
I added the entire code of that page now , it's not much, but as stated: I added the binding source and displaymember "researchtype" to the combobox.
So when i start the form, i can choose a type of research.
Now i need to show the description of the research in the richtextbox
In the Form.Load...
I have a function that returns a DataTable that contains columns called Name and Type. I bind the ComboBox to the DataTable and set the DisplayMember to "Name". Each Item in the ComboBox contains the entire DataRowView. I set the TextBox to the first row (dt(0)("Type")) Type column value so the correct information will be displayed for the initial selection.
I put the code to change the textbox display in ComboBox1.SelectionChangeCommitted because the other change events will produce a NRE since .SelectedItem has not yet been set when the form loads. The commited event will only occur when the user makes a selection.
First, cast the SelectedItem to its underlying type, DataRowView. Then you want the value of the Type column. This value is assigned to the text property of the textbox.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = LoadCoffeeTable()
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Name"
TextBox1.Text = dt(0)("Type").ToString
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
TextBox1.Text = DirectCast(ComboBox1.SelectedItem, DataRowView)("Type").ToString
End Sub
Just substitute Researchtype for Name and Researchdetails for Type.
After using 'OleDbDataAdapter' to fill the dataset, you can set 'DisplayMember' and 'ValueMember' for your ComboBox. Every time the index of your ComboBox changes, it's 'ValueMember' will be displayed in richtextbox.
Here's the code you can refer to.
Private dataset As DataSet = New DataSet()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connString As String = "your connection String"
Using con As OleDbConnection = New OleDbConnection(connString)
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.CommandText = "SELECT Researchtype, Researchdetails FROM yourtable"
Dim adpt As OleDbDataAdapter = New OleDbDataAdapter(cmd)
adpt.Fill(dataset)
End Using
ComboBox1.DisplayMember = "Researchtype"
ComboBox1.ValueMember = "Researchdetails"
ComboBox1.DataSource = dataset.Tables(0)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
RichTextBox1.Text = ComboBox1.SelectedValue.ToString()
End Sub
Result of my test.

No New Row Entry Added to Access Backend

so I made this code which is supposed to update the Delivery table in my MS Access database. The code runs fine and even says that data entry is successful, but upon checking the database file no new row entry is made.
Public Class NewDelivery
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim con As New OleDb.OleDbConnection
Public Shared stxtboxsupsel As TextBox
Public Shared supnum As String
Public Shared dgvitems As DataGridView
Private Sub NewDelivery_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "MM/dd/yyyy"
End Sub
Private Function OpenDBConnection()
If My.Settings.DatabaseLoc = "" Then
Dim directory As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Return "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & "\IE156.mdb"
Else
Return "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & My.Settings.DatabaseLoc
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
My.Forms.ManageInventory.Show()
Me.Close()
End Sub
Private Sub btnSelSupp_Click(sender As Object, e As EventArgs) Handles btnSelSupp.Click
My.Forms.SelectSupplier.Show()
stxtboxsupsel = txtboxsupsel
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
con.ConnectionString = OpenDBConnection()
con.Open()
Dim sql As String = "INSERT INTO Delivery(ItemPurchDate,SupNum) VALUES (#ItemPurchDate,#SupNum)"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("#ItemPurchDate", DateTimePicker1.Text)
cmd.Parameters.AddWithValue("#SupNum", supnum)
con.Close()
Me.Close()
MsgBox("New Delivery Recorded")
End Sub
The Delivery Table has 3 columns namely ItemPurchNum (Primary Key and Autonumber), ItemPurchDate(date/time) and SupNum(Number and has a many to one relationship with SupNum from my Supplier table).
I had no trouble adding new rows in my other forms following the similar code. Any thoughts on why it won't add a new row? Thank you in advance!
thanks for your help. Noticed that I skipped a line cmd.ExecuteNonQuery(), and now it works!

How to do a database search using a textbox and a search button in visual studio VB Code

I want to type something in my txtSearchCriteria textbox and when I hit the Perform Search button it displays all the records it finds into the other textboxes I have in my form. I am using a localdb file with a dataset in Visual Studio 2012. So far I have everything working except the search button. Here is my entire code in my project.
'Import Namespaces for SQL
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1 Dim objCurrencyManager As CurrencyManager
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Loads data into the 'CustomersDataSet.Customers' table.
Me.CustomersTableAdapter.Fill(Me.CustomersDataSet.Customers)
'Controls Record Number Movement
objCurrencyManager = CType(Me.BindingContext(CustomersBindingSource), CurrencyManager)
'Display the current record number
Position()
'Display a tool tip at the bottom of screen
lblToolStripLabel1.Text = "Ready To Compute Data"
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'Used try catch block to validate all fields to ensure proper use of form and to display error if required fields are missing user imput
Try
Me.Validate()
Me.CustomersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.CustomersDataSet)
lblToolStripLabel1.Text = "Record Saved" 'Display that record has been saved
Catch ex As Exception
MsgBox(ex.Message)
End Try
Position()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
'code to update an existing record and display that redord was updated successfully
Try
Me.Validate()
Me.CustomersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.CustomersDataSet)
lblToolStripLabel1.Text = "Record Updated" 'display record updated
Catch ex As Exception
MsgBox(ex.Message)
End Try
Position()
End Sub
Private Sub dtnDelete_Click(sender As Object, e As EventArgs) Handles dtnDelete.Click
' Removes the current record and displays the new position in the database
Me.CustomersBindingSource.RemoveCurrent()
Position()
End Sub
Private Sub btnMoveFirst_Click(sender As Object, e As EventArgs) Handles btnMoveFirst.Click
'Moves the current record to the begining of the dataset. The First Record
Me.CustomersBindingSource.MoveFirst()
Position()
End Sub
Private Sub btnMovePrevious_Click(sender As Object, e As EventArgs) Handles btnMovePrevious.Click
'moves to the previous record and displays the position
Me.CustomersBindingSource.MovePrevious()
Position()
End Sub
Private Sub btnMoveNext_Click(sender As Object, e As EventArgs) Handles btnMoveNext.Click
'Moves to the next record in the dataset
Me.CustomersBindingSource.MoveNext()
Position()
End Sub
Private Sub btnMoveLast_Click(sender As Object, e As EventArgs) Handles btnMoveLast.Click
'Moves to the last Record in the Dataset
Me.CustomersBindingSource.MoveLast()
Position()
End Sub
Private Sub Position()
'This code displays the positio of the current record the user is viewing and shows it out of the number of recors that are held in the dataset
txtRecordPosition.Text = objCurrencyManager.Position + 1 & " Of " & objCurrencyManager.Count()
End Sub
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
'Clears the form for user imput, Created a new record and adds the current date to CustomerDate field and adds the next CustomerNumber available.
Me.CustomersBindingSource.AddNew()
txtCustomerNumber.Text = Me.CustomersBindingSource.Count + 1
txtCustomerDate.Text = Date.Today.ToShortDateString
End Sub
Private Sub btnPerformSort_Click(sender As Object, e As EventArgs) Handles btnPerformSort.Click
'Code to Sort by different field within the dataset
Select Case cboField.SelectedIndex
Case 0 'CustomerNumber
CustomersBindingSource.Sort = "CustomerNumber"
Case 1 'First Name
CustomersBindingSource.Sort = "FirstName"
Case 2 'Last Name
CustomersBindingSource.Sort = "LastName"
Case 3 'City
CustomersBindingSource.Sort = "City"
Case 4 'Province
CustomersBindingSource.Sort = "Province"
End Select
btnMoveFirst_Click(Nothing, Nothing)
lblToolStripLabel1.Text = "Records Sorted"
End Sub
Private Sub btnPerformSearch_Click(sender As Object, e As EventArgs) Handles btnPerformSearch.Click
'This will take the user imput from the txtSearchCriteria textbox and return all records that have the criteria
End Sub
End Class
Here is a sample to query database assuming you are connecting to sql server.
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("<your connection string name>").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT ContactName, City, Country FROM Customers WHERE ContactName LIKE '%' + #ContactName + '%'"
cmd.Connection = con
cmd.Parameters.AddWithValue("#ContactName", txtSearch.Text.Trim())
Dim dt As New DataTable()
Using sda As New SqlDataAdapter(cmd)
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Sub
To explain at first step we are declaring connection string then we are opening SqlConnection object and then we are querying the database table ContactName based on the txtSearch value inputted.Next we are filling the dataset and binding the grid.
I suggest you to read this msdn article on sql connection.

Datagridview and access database only updates after clicking a different row

I am reading an access database and populating the info in datagridview. My form has a DGV, and 3 buttons.
Button one copies the selected row to a datetimepicker control.
Button two copied the updated datetimepicker value back to the DVG
Button three does an update (writes the info back to the database).
My issue is that the info only gets updated in the database if I select a different row before hitting button three. I am not getting any error message in either case.
Below is my code. The database only has 2 columns (name and DOB - which is date/time).
Public Class Form1
Dim dbConn As New OleDb.OleDbConnection
Dim sDataset As New DataSet
Dim sDataAdapter As OleDb.OleDbDataAdapter
Dim sql As String
Dim iTotalRows As Integer
Dim sShipTypeFilter As String
Dim sBuildingFilter As String
Dim sCustSuppFilter As String
Dim sStatusFilter As String
Dim sDayFilter As String
Dim dv As New DataView
Sub myDBConn()
dbConn.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\terry\Documents\Database1.accdb"
Debug.Print("Start:" & DateAndTime.Now.ToString)
dbConn.Open()
sql = "select * from TableX"
sDataAdapter = New OleDb.OleDbDataAdapter(Sql, dbConn)
sDataAdapter.Fill(sDataset, "MyTable")
dbConn.Close()
iTotalRows = sDataset.Tables("MyTable").Rows.Count
Debug.Print("Rows from Access:" & iTotalRows)
Debug.Print("End:" & DateAndTime.Now.ToString)
End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Call myDBConn()
Debug.Print("DVG1 row count before binding:" & DataGridView1.Rows.Count)
'dv = New DataView(sDataset.Tables(0), "Shipment = 'Regular' and Building = 'CSE'", "Company DESC", DataViewRowState.CurrentRows)
dv = sDataset.Tables(0).DefaultView
Debug.Print("DataView count:" & dv.Count)
DataGridView1.DataSource = dv
Debug.Print("DVG1 Rows:" & DataGridView1.Rows.Count)
DataGridView1.Columns("DOB").DefaultCellStyle.Format = "hh:mm tt"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
dtp1.Value = DataGridView1.SelectedRows(0).Cells("DOB").Value
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
End Sub
End Class
Before updating you need to Endedit. This means you need to add Endedit for the datagridview.
So this will be your code:
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
Datagridview1.EndEdit()
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
EDIT1:
Dim dt As New DataTable
dbConn.Open()
sDataset.Tables.Add(dt)
sDataAdapter = New OleDbDataAdapter("Select * from TableX", dbConn)
sDataAdapter.Update(dt)
dbConn.Close()
I figured it out - thanks Stef for putting me on the right track.
My DGV is only updated programmatically (not by user edits) so I updated the code for button 2 to set the editmode, begin editing, update the selected DVG row and end editing:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically
DataGridView1.BeginEdit(True)
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
DataGridView1.EndEdit()
End Sub
After doing this modification - my datadapter.update command works!!