Crystal Report dynamic datasource not creating report - asp.net

I have Googled on this subject and I have coded as per what I saw, but the CrystalReportViewer is empty and I am not getting any errors. I am not sure what I am doing wrong. Below is all of my code.
strSQL = "select * from MMM_vw_Rpt_Summary where BudgetID = " & Master.lblBudgetIDText
ds = CreateDataset(strSQL, "cnn_rcg_mmm", "dt_Summary")
CreateSummary(ds)
Public Shared Function CreateDataset(ByVal strSQL As String, ByVal strCNN As String, ByVal strTable As String) As DataSet
Dim strConnString As String = ConfigurationManager.ConnectionStrings(strCNN).ConnectionString
Dim da As MySqlDataAdapter
Dim ds As DataSet
Dim strReturn As String
strReturn = ""
Try
Using con As New MySqlConnection(strConnString)
Dim cmd As New MySqlCommand(strSQL, con)
con.Open()
da = New MySqlDataAdapter(cmd)
ds = New dsLifeBudget
da.Fill(ds, strTable)
Return ds
con.Close()
End Using
Catch ex As Exception
strReturn = ex.Message
End Try
End Function
Protected Sub CreateSummary(ByVal ds As DataSet)
Dim strReportPath As String = Server.MapPath("~/Reports/LB_Summary.rpt")
Dim cr As New ReportDocument
Dim strError As String = ""
Master.HideMsg()
'Verify the path to the Crystal Report's .RPT file
If Not IO.File.Exists(strReportPath) Then
Throw (New Exception("Unable to locate report file:" & vbCrLf & strReportPath))
strError = "Unable to locate report file: " & strReportPath
Master.txtMsgText = "Error creating Summary - " & strError
Master.txtMsgVisible(True)
Exit Sub
End If
crLifeBudget.HasDrillUpButton = False
crLifeBudget.Height = "300px"
crLifeBudget.Width = "500px"
'Load the Crystal report's .RPT file and pass in the DataTable
cr.Load(strReportPath)
cr.SetDataSource(ds.Tables("dt_Summary"))
crLifeBudget.ReportSource = cr
crLifeBudget.RefreshReport()
End Sub
Any help would be greatly appreciated!
Eddi Rae

Try referring the following, It could solve the problem since your code lacks thecrLifeBudget.refresh() line.
Crystal Reports empty when printed during runtime

Related

Getting error for Data Reader in vb.net

Im facing the error when execute the data reader command in vb.net. it throw handling. This field like when you enter employee id in textbox then it will capture in database for other field name,department.
here is my code
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String =ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Dim sqlQuery As String = "SELECT * hr_record WHERE Emplid='" & txt1.Text & "'"
Using sqlConn As New MySqlConnection(strConnectionString)
Using sqlComm As New MySqlCommand()
With sqlComm
.CommandText = sqlQuery
End With
Try
sqlConn.Open()
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
TextBox2.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
Try to change your select query like
Dim sqlQuery As String = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
Note:- Cannot use code like that in Page_Load.Try to make one Function and call that function from Page_Load and always use Parameterized query.
Updated answer:
Page_Load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
DataBind()
End Sub
Outside Method:
Public Sub DataBind()
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New MySqlConnection(sConnection)
Con.Open()
Using Com As New MySqlCommand("SELECT * from hr_record WHERE Emplid='"txt1.Text
"'", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txt1.Text = RDR.Item("Emplid").ToString()
TextBox1.Text = RDR.Item("Nama").ToString()
TextBox2.Text = RDR.Item("DeptDesc").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
End Sub
Note:Try to implement your logic like that and also modified as per your requirements.
Hope it works.
You try to get Emplid in page load,but it's still nothing you should use button to check if Emplid exist
Thanks to all thanks helping me..finally this code it works thanks to all .
this the code will be function
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Using sqlConn As New MySqlConnection(strConnectionString)
sqlConn.Open()
Using sqlComm As New MySqlCommand()
sqlComm.Connection = sqlConn
With sqlComm
.CommandText = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
End With
Try
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
txtdep.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
sqlConn.Close()
End Using
End Using
End Sub

Deleting a row from gridview bound manually?

I have a gridview which is bound to a table that allows to download files. The table consists of:
tableid as int
filename as string
filepath as string
delete (added column in the gridview)
This deletion is not automatic, it is coded. I want the user to click on delete and the row selected will be deleted. Simple as that, but I cant seem to get the ID of the row to be deleted. This is what I have done:
Try
'Get the Image_Id from the DataKeyNames
Dim imgId As Integer = Convert.ToInt32(gvDetails.DataKeys(e.RowIndex).Value)
Dim cmd As New SqlCommand("delete from FilesTable where id=#id", con)
cmd.Parameters.AddWithValue("#id", imgId)
cmd.CommandType = CommandType.Text
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
End Try
But I keep getting error that string output cannot be converted to Integer:
Error Occurred: Input string was not in a correct format.
Please Help!
This is how the grid view is bound:
Private Sub BindGridviewData()
Try
con.Open()
Dim cmd As New SqlCommand("select * from FilesTable", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
con.Close()
gvDetails.DataSource = ds
gvDetails.DataBind()
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub
I found the answer after a long time and it was a simple problem:
Instead of:
Dim imgId As Integer = Convert.ToInt32(gvDetails.DataKeys(e.RowIndex).Value)
I changed it into:
Dim imgId As Integer = Int32.Parse(gvDetails.Rows(e.RowIndex).Cells(0).Text)

Creating Control Arrays in Vb 2010 with table column names not reading Rows

I am having problems with Creating Control Arrays and getting the Column Names for a table, I know that my string works as I have used the outputted string straight as a SQL query, the problem lies where it seems not to find any of the rows in the table(that i know are their, using the If lrd.HasRows Then I have seen that it does not find any rows (lrd.HasRows = False). Is their a diffent Connection string for INFORMATION_SCHEMA.COLUMNS ?
'Finds the Column Name
Public Sub findSQLColumnName(ByRef i As Integer, ByRef OutputValue As String, ByVal tableName As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim lrd As SqlDataReader
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
Call FindConnectionString(con) ' finds connection string
cmd.Parameters.Add(TableNameParm)
cmd.Parameters.Add(LocationParm)
Call SQLSELECT_WHERE("INFORMATION_SCHEMA.COLUMNS", "COLUMN_NAME AS Output, ORDINAL_POSITION", True, " (TABLE_NAME = #Tablename) AND (ORDINAL_POSITION = #Location)", con, cmd, lrd)
Try
' While lrd.Read() ' code writen within here for what is to be done with selected data.
'Call findSQLColumnValue("Output", lrd, OutputValue)
'End While
If lrd.HasRows Then
lrd.Read()
Call findSQLColumnValue("Output", lrd, OutputValue)
lrd.Close()
'Close connection before Redirecting.
Else
lrd.Close()
End If
' Catch ex As Exception
Finally
con.Close()
End Try
End Sub
'Finds the value of a Column
Public Sub findSQLColumnValue(ByRef ColumnName As String, loader As SqlDataReader, ByRef OutputValue As String)
OutputValue = (Convert.ToString(loader(ColumnName))).Trim
End Sub
'Button Click (Creates the control array)
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim SQLCode As New SQLCode
Dim TableLength As Integer
Dim lblText(100) As String
Call SQLCode.SQLFindNoColumns("PatientClinicalinformation", TableLength, lblTitlePatient, lblText)
For i As Int16 = 1 To TableLength
' Create the label control and set its text attribute
Dim Label2 As New Label
Call SQLCode.findSQLColumnName(i.ToString, lblText(i), "PatientClinicalinformation")
Label2.Text = lblText(i)
Dim Literal2 As New Literal
Literal2.Text = "<br />"
' Add the control to the placeholder
PlaceHolder1.Controls.Add(Label2)
Label2.ID = "lbl" & i
PlaceHolder1.Controls.Add(Literal2)
Next
End Sub
'SelectWhere
Public Sub SQLSELECT_WHERE(ByVal Tables As String, ByVal Columns As String, ByVal WHERE As Boolean, ByVal WHEREStatement As String, ByRef connection As SqlConnection, ByRef command As SqlCommand, ByRef loader As SqlDataReader)
connection.Open()
command.Connection = connection
If WHERE = False Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables
End If
If WHERE = True Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables & " WHERE " & WHEREStatement
End If
command.CommandText = command.CommandText
loader = command.ExecuteReader()
End Sub
I found the solution! the code all worked there was a problem with the array TableNameParm
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
The TableNameParm.Direction should be an input but is set to a Output
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Input
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
It's hard to say without knowing the function SQLSELECT_WHERE, but it's possible one or more of the parameters is not correct. Try skipping that function and use
cmd = New SqlCommand("SELECT ... WHERE", conn)
You can also test the number of rows by using count(*) in the query.

Exception Error must be type IListSource, IEnumerable or IDataSource. Gridview

I get a catch exp as Exception Error in which says, data source is an invalid type, it must either be of the type IListSource, IEnumerable or IDataSource.
This error comes when I try to add a new record to a database through a gridview, so I get the data from database nicely into this gridview, therefore I do not understand that I get a catch exp as exception when the database is not unavailable.
The #thesli_number OleDbType.VarChar Value = thenumber is type of number in the db.
'Add new record to DB
Protected Sub AddNewTask(ByVal sender As Object, ByVal e As EventArgs)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("txttestcat"), TextBox).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("txttestinfo"), TextBox).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("txttestnumber"), TextBox).Text
Dim strSQL As String = ""
strSQL = "" & _
"INSERT INTO [TableTest] " & _
"([test_cat], [test_info], [test_number])" & _
"VALUES (#thesli_cat, #thesli_info, #thesli_number)"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.VarChar).Value = thenumber
GridView1.DataSource = cmd
GridView1.DataBind()
'MsgBox("Row(s) Added !! ")
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
EDIT................EDIT.................EDIT...................EDIT
Ok i can now add data to the gridview, i can delete a record and i can add a new record.
But i cant get the update event to work, can u see whats wrong in this new code !?
'Update record
Protected Sub UpdateTask(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim theid = Convert.ToInt32(DirectCast(GridView1.FooterRow.FindControl("lbltestid"), Label).Text)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("lbltestcat"), Label).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("lbltestinfo"), Label).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("lbltestnumber"), Label).Text
Dim strSQL As String = ""
strSQL = "" & _
"UPDATE [TableTest] " & _
"SET [test_cat] = #thesli_cat, [test_info] = #thesli_info, [test_number] = #thesli_number " & _
"WHERE [test_id] = #thesli_id"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_id", OleDbType.Integer).Value = theid
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.Integer).Value = thenumber
cmd.ExecuteNonQuery()
'MsgBox("Row(s) Updated !! ")
GridView1.EditIndex = -1
GetRecords()
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
If the answer to your original question was answered in my comment above (posted below here in quotes), then you should mark this question as answered, then post an entirely new question so you get more accurate responses. This question no longer applies to your actual problem.
My answer which, in your comment, solved your original question:
That example (referring to the link in your comment above) does not directly assign an
OleDbCommand to the DataSource, because it
can't. If you look at the example the author passes the cmd variable
to the GetData function GetData(cmd), which more than likely executes
the stored procedure and returns a DataSource supported type (e.g.
IListSource, IEnumerable or IDataSource).

Object reference not set to an instance of an object. splitItems(0).toString

i have this button which i add in row of data however, it give me error, can anyone help me out tell me why is the splitItems(0).ToString cause error, how should i get that value to store in the database
Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
Dim rowIndex As Integer = 0
Dim sc As New StringCollection()
If ViewState("CurrentTable") IsNot Nothing Then
Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count < 10 Then
For i As Integer = 1 To dtCurrentTable.Rows.Count
'extract the TextBox values
Dim box5 As TextBox = DirectCast(Gridview3.Rows(rowIndex).Cells(1).FindControl("TextBox5"), TextBox)
'get the values here
Dim box6 As Date
box6 = Convert.ToDateTime(box5.Text)
Dim box7 As Date = Convert.ToDateTime(box5.Text)
sc.Add(box6)
rowIndex += 1
Next
InsertRecords(sc)
End If
Else
' lblMessage.Text = "Cannot save as there no information recorded"
MsgBox("failed")
End If
End Sub
Protected Sub InsertRecords(sc As StringCollection)
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
End If
Next
Try
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ConfigurationManager.ConnectionStrings("mydatabase").ConnectionString
Dim cmd As String
cmd = "Insert into Date values (#date) "
myCmd.CommandText = cmd
myCmd.CommandType = CommandType.Text
//error found at this line splitItems(0).ToString()
myCmd.Parameters.Add(New SqlParameter("#date", splitItems(0).ToString()))
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myCmd.Dispose()
myConn.Dispose()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
End Sub
Please check with the breakpoint and make sure splitItems has more than one values.
You will probably find that either there are no elements in the splitItems array, or the element splitItem(0) equals "Nothing".
Just briefly looking at your code I wonder if the main problem is in the ForEach at the top of InsertRecords. I think if sc = {"1/1/2010"} then the "If item.contains(",")" will never be true so the date will never be added to the splitItems array. A.K.A the splitItems array would be empty when it hits the ToString line that is throwing the exception.

Resources