Crystal Reports Show Only The last Column - vb.net

I want to display a Table in crystal reports but its show only the last column, this is my code :
Try
Cursor = Cursors.WaitCursor
Dim id As Integer = 1
Dim Report1 As New PrintStockReport
Dim dt As DataTable = New DBConnect().selectdata( _
"SELECT StockTable.StockRef, StockTable.StockCat FROM StockTable;")
'Report1.SetDataSource(dt)
For i As Integer = 0 To dt.Rows.Count - 1
Report1.SetParameterValue("StockID", id)
Report1.SetParameterValue("StockRef", dt.Rows(i)(0).ToString)
Report1.SetParameterValue("StockCat", dt.Rows(i)(1).ToString)
id += 1
Next
CrystalReportViewer1.ReportSource = Report1
Cursor = Cursors.Default
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
but, when I set the Datasource its show " the report has no tables", can anyone explain to me why I get this issue? thanks
Report1.SetDataSource(dt)

First lets get your VB code fixed. Remove the For/Next loop completely, and then uncomment the line above it. Your code should now look like this:
Try
Cursor = Cursors.WaitCursor
Dim id As Integer = 1
Dim Report1 As New PrintStockReport
Dim dt As DataTable = New DBConnect().selectdata( _
"SELECT StockTable.StockRef, StockTable.StockCat FROM StockTable;")
Report1.SetDataSource(dt)
CrystalReportViewer1.ReportSource = Report1
Cursor = Cursors.Default
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
This will properly bind your datatable to the Report1 object as a data source. Now you need to fix your report in the designer by removing the parameter fields from the report. Parameter Fields are only used when you need the user to pass input into the report at runtime. For example, if I were making a report that shows data for a single financial period to the user and I want it to be flexible enough to work with any period, I would use a Parameter Field to ask the user to provide the period as input when the report is executed. If you look at the Field Explorer in your report designer you should see "Database Fields". When expanded this should show you the table or tables that are defined as the report's database. Expanding a table will then show you the list of fields available to the report. Drag the fields you want displayed on your report to the section where they should appear.
Once this is done, your report should work. This assumes you have your database defined within the database expert in the report designer though.

Related

Fill a specific column of datagridview from Informix vb.net

I'm filling a DataGridView but I cannot find how to fill an specific column of the datagridview. The connection string and filling the table works fine.
I'm getting ID,Name,Surname,Country,Age from the database and inserting those in the table but I want the columns to be in a specific column because I also the table with data from another tables.
Example I want the column 2 to have the country, the column 3 to have the id, etc, in a different order than how it's stored in the database
How do I appoint in which column I want the data from the SQL to be stored?
Public Shared Sub listar(tipo As String, tabla As DataGridView)
Try
If connect() Then
comando.CommandText = "SELECT * FROM " & tipo
comando.ExecuteNonQuery()
dataAdapter.SelectCommand = comando
dataAdapter.Fill(dataSet, tipo)
tabla.DataSource = dataSet.Tables(tipo)
closeConn()
End If
Catch ex As Exception
MsgBox("ERROR")
End Try
End Sub

List View Population Errors

I have 3 columns that need populating when a user presses 'search' however every time that I click 'search' only the Employee ID appears, neither the 'First Name' nor the 'Last Name' are present in the List View. The data does exist in my Access Database, this is proved as the program produces a blank record instead of a null value error. The code that I am using to populate the List View is:
ds.Clear()
lstClockin.Items.Clear()
con.ConnectionString = provider & datafile
con.Open() 'Open connection to the database
sqlstatement = "SELECT * FROM [EmployeeAccounts]"
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "allmembers") 'Fill the data adapter
con.Close()
Dim recordCount, x As Short
recordCount = 0
x = 0
recordCount = ds.Tables("allmembers").Rows.Count
With ds.Tables("allmembers")
Do Until x = recordCount
lstClockin.Items.Add(.Rows(x).Item(0))
lstClockin.Items(x).SubItems.Add(.Rows(x).Item(1))
lstClockin.Items(x).SubItems.Add(.Rows(x).Item(2))
lstClockin.Items(x).SubItems.Add(.Rows(x).Item(3))
x = x + 1
Loop
End With
The first 3 columns in the Database are, [Employee ID], [First Name] & [Last Name]
Any suggestions are welcome; however I have ruled out using a DataGridView or any control. As this program needs to use a ListView. Thankyou in advance!
There are several things that can be improved in the code:
Dim SQL = "SELECT Id, Name, Fish FROM Sample"
Using dbcon As New OleDbConnection(ACEConnStr)
Using cmd As New OleDbCommand(SQL, dbcon)
dbcon.Open()
Dim lvi As ListViewItem
myLV.SuspendLayout()
Using rdr = cmd.ExecuteReader
Do While rdr.Read
lvi = New ListViewItem(rdr.GetInt32(0).ToString)
If rdr.IsDBNull(1) Then
lvi.SubItems.Add("")
Else
lvi.SubItems.Add(rdr.GetString(1))
End If
If rdr.IsDBNull(2) Then
lvi.SubItems.Add("")
Else
lvi.SubItems.Add(rdr.GetString(2))
End If
myLV.Items.Add(lvi)
Loop
End Using
myLV.ResumeLayout()
End Using
End Using
Connections and other DB Provider objects allocate resources which need to be released or your app will leak. Using blocks for things that implement Dispose will close and dispose of them for you
There is no need for an DataAdapter, DataSet and DataTable since you are copying the data to the control. This code uses a DataReader to get the data.
Rather than SELECT * the query specifies the columns/order so it can use the Getxxxxx methods to get typed data. That doesnt matter a great deal in this case because everything gets converted to string for the ListView. lvi.SubItems.Add(rdr(COLUMN_NAME).ToString()) would also work.
It seems unlikely the ID column could be null, so the code only checks the other 2 for DbNull (another thing the DGV can handle without help).
Since the ListView is suboptimal and slow in adding items, SuspendLayout and ResumeLayout are used to minimize paints while it is populated.
I am not at all sure what ...the program produces a blank record means, but in order use a ListView like it is a grid, the View property must be Details and you have to have added 3 columns in the IDE (or manually create them in code). Nothing will show without those settings.
If the DataTable is needed/used elsewhere, you can still fill one without a DataAdpater and populate the LV from it:
...
dt.Load(cmd.ExecuteReader)
For Each row As DataRow In dt.Rows
lvi = New ListViewItem(row(0).ToString())
If DBNull.Value.Equals(row(1)) Then
lvi.SubItems.Add("")
Else
lvi.SubItems.Add(row(1).ToString())
End If
If DBNull.Value.Equals(row(2)) Then
lvi.SubItems.Add("")
Else
lvi.SubItems.Add(row(2).ToString())
End If
myLV.Items.Add(lvi)
Next
This uses a different DBNull check since it is using a DataRow and not the DataReader.

VB.Net Fill List with SQL Query

I'm trying to fill either a combobox or a list with an sql query, I can get them to produce the number of entries pulled but not the names of the entries, and not multiple entries.
The code in question is simple:
Dim RegisterApt As New StudentsDataSetTableAdapters.TestTableAdapter
Try
txtTestPull.Items.Add(RegisterApt.FillByStudentsTest(StudentsDataSet.Test, StudentInsert.School, StudentInsert.School))
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
What I can't seem to find online is how to do this.
All I'd like to do is pull results using my sql query which I know works,
and push the resulting rows to the list or combobox
Here's the step by step on how to fill a ComboBox and a DataGridView using ADO.Net. I use the Northwind database as a sample.
1. Add a DataSet
Right-click your project and choose Add, then choose New Item. Choose Dataset in the next window.
2. Add a DataTable
Connect to your database and drag a table into the middle area. In this example, I choose the Customers table.
3. Add a query
Right-click your DataTable, and choose Add, then choose Query.
Choose Use SQL statements in the next window, click Next.
Choose SELECT which returns rows in the next window, click Next.
4. Write a query
SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax
FROM dbo.Customers
WHERE Country = #Country
I add a WHERE clause to filter the data. Click Next.
Gives names to your methods. I use FillByCountry in the first textbox and GetDataByCountry in the second textbox.
Save your project and build it first because you're adding a new DataSet.
5. Add some controls in your form
Add a Button, a TextBox, a ComboBox and a DataGridView. You can change the names, but I use the default names in this example.
6. Write some code to get the data and bind it to ComboBox and DataGridView
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
' declare a DataTable
Dim dt As New DataSet1.CustomersDataTable
' declare a DataAdapter
Dim da As New DataSet1TableAdapters.CustomersTableAdapter
' use the DataAdapter to fill the DataTable
da.FillByCountry(dt, TextBox1.Text)
' bind the DataTable to a DataGridView
DataGridView1.DataSource = dt
' bind the DataTable to a ComboBox
ComboBox1.DataSource = dt
ComboBox1.ValueMember = "CustomerID"
ComboBox1.DisplayMember = "CompanyName"
End Sub
End Class
7. Run the project and see the result

How to write query based on datagridview results?

Hi I have a query which populates a datagridview which all works correctly. When the datagrid has been populated it has the following columns
UserID
UserName
UserDepot
I have a button which when pressed I would like to run another query based on the information in column UserID and whatever row is selected. I am having difficulty writing this query as I dont know what command I need to write in order to call this information
the datagrid is called dg_usersearch so I was expecting to use something like dg_usersearch.selectedvalue but selectedvalue isnt a member of datagridview does anyone know what command I should be using?
The query for filling the datagrid is as follows
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'creates a list of all incidents as per the search parameters
Dim dt As New DataTable
Dim query As String = "select [userid],[username],[userdepot] from [tbluser]"
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyDATASOURCE")
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
'checks to make sure query has results
If dt.Rows.Count > 0 Then
dgusersearch.DataSource = dt
'if no results display the following message
ElseIf dt.Rows.Count = 0 Then
MsgBox(Prompt:="No results for search request, please try again")
End If
Answered by #Plutronix above,
myDGV.SelectedRows(0).Cells(0).Value.ToString()

how to get data to textbox from the database

I have a form with one combo box and text box, and an SQL database
named balance with two columns; one as customername and the other as obbalance.
I had bound all of the customer name to the combo box, now what I have to do is,
when a user selects a customer name from the combo box, the text box should show the obbalance of the selected customername; here, the customer name will not be repeated - only one name per customer.
What can I do? Please help me.
Dim conectionstring As String
conectionstring = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
MessageBox.Show(TextBox1.Text)
Dim result As Object
Try
sqlcon.Open()
' Dim sdr As SqlDataReader = sqlcmd.ExecuteReader()
result = sqlcmd.ExecuteScalar()
If result IsNot Nothing Then
TextBox1.Text = result.ToString()
MessageBox.Show(TextBox1.Text)
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I've tried this, but I can't see the value in the text box, and obbalance is a floating-point value from the SQL database.
If you're updating a text box, is this a single result (scalar value)? If so, the first thing I'd do is use ExecuteScalar not ExecuteReader. Then, use debug mode with breakpoints to get a better idea of what is actually happening. It may simply be that you're not getting any results.
Note: I'm assuming the bad coding practice (in-line sql statement, hard-coded connection string, etc.) are for clarity. If they're not, fix them.
Make the follwing changes:
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = '" & ST & "'", sqlcon)
TextBox1.Text = sdr.GetString(yourColumnIndex)
ComboBox1.SelectedText returns the highlighted (selected) text on the ComboBoxControl. That will be empty if you haven't use your mouse to select a portion of its text or hold the shift while you are pressing the direction keys on your keyboard. And that's probably why your query returns ZERO RECORDS.
Use the following instead:
Dim ST As String = ComboBox1.SelectedItem.Text
Set a breakpoint and ensure you are getting the value for OBBALANCE (see if you are getting any rows period might be good). Also, make sure you can only get one row, as you are iterating forward, even when you only need one value.
Better yet, consider ExecuteScalar, which only returns a single value. While you are at it, parameterize the SQL query so you don't get SQL injected.
UPDATE: Just change it here:
sdr = sqlcmd.ExecuteReader()
to something like
Dim s as String = sqlcmd.ExecuteScalar()
Then use s as your textbox value. You may have to ToString() the value or otherwise cast as string, as I believe the ExecuteScalar() returns an object.