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)
Related
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
I have an asp.net web form application to bind data (REFERENCE_NO) to a DropDownList (ddlRef) .ddlRef retrieves data from a MySql database based on the selected date in a BasicDatePickerControl (bdpApps) . My code is as below:
Protected Sub loadRefnumbers()
Try
cmd = New MySqlCommand("select idapp,REFERENCE_NO from ONLINELOANS where APPLICATION_DATE ='" & DateFormat.getSaveDate(bdpApps.SelectedDate) & "'", con)
adp = New MySqlDataAdapter(cmd)
Dim ds As New DataSet
ds.Clear()
adp.Fill(ds, "DATE_REFS")
If ds.Tables(0).Rows.Count > 0 Then
ddlRef.DataSource = cmd.ExecuteReader()
ddlRef.DataTextField = "REFERENCE_NO"
ddlRef.DataValueField = "idapp"
ddlRef.DataBind()
Else
ddlRef.DataSource = Nothing
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I have a getSaveDate function that converts the date format in the basicdatepicker control to the MySql Date format (YYYY-MM-DD). When i debug the app the ddlRef control is not updating to reflect the values from REFERENCE_NO column. Is there anything wrong with my SQL command?
Solution for question above.For those who use BasicDatePicker 1_4_3 in asp.net webforms the code for my problem is to call the query on the SelectionChanged handler for the datepicker control:
Protected Sub bdpApps_SelectionChanged(sender As Object, e As EventArgs) Handles bdpApps.SelectionChanged
con = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
Using cmd As New SqlCommand("SELECT id,REFERENCE_NO from ONLINELOANS where APP_DATE='" & DateFormat.getSaveDate(bdpApps.SelectedDate) & "'")
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
ddlRef.DataSource = cmd.ExecuteReader()
ddlRef.DataTextField = "REFERENCE_NO"
ddlRef.DataValueField = "idapp"
ddlRef.DataBind()
ddlRef.Items.Insert(0, New ListItem("--SELECT--", "0"))
ddlRef.SelectedIndex = 0
con.Close()
End Using
End Sub
I got 1 checkboxlist with 6 checkboxes inside it (below is my database)
id : int
interest : bit
When I click one checkbox, the value is saved to my database as TRUE. Here is my code:
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim insertSql As String = "INSERT INTO tbinterest(interest) VALUES(#interest)"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(insertSql, myConnection)
myCommand.Parameters.AddWithValue("#interest", SqlDbType.Bit).Value = 1
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
But somehow, when I load the page, it does not show the checked state (checked/unchecked). Here is my code in page load. Can you help me out? Thanks.
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using myConnection As New SqlConnection(connectionString)
Dim objCmd_team As SqlCommand = New SqlCommand("SELECT [interest] FROM [tbinterest]", myConnection)
myConnection.Open()
Dim objReader As SqlDataReader = objCmd_team.ExecuteReader()
While (objReader.Read())
Dim currentCheckBox As ListItem = chkApprovers.Items.FindByText(objReader("interest"))
If currentCheckBox IsNot Nothing Then
currentCheckBox.Selected = True
End If
End While
End Using
your code seems to be correct.. please check this line with break point that listitem has value or not.
Dim
currentCheckBox As
ListItem =
chkApprovers.Items.
FindByText(objReader
("interest"))
If listitem is nothing then try this
Dim
currentCheckBox As
ListItem =
chkApprovers.Items.
FindByText(objReader.Item
("interest").ToString)
And one more thing, you are saving only bit value as interest then how did you match this with your checkbox.
you can match only with checkboy text value or id value
Hope this help.
I am trying to run this code below. It was working previously, but when I added a second datareader, it stopped. Can anyone tell me what's wrong ?
Protected Sub btnSearchUser_Click(sender As Object, e As EventArgs) Handles btnSearchUser.Click
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim searchComm As String = "SELECT * FROM users WHERE username LIKE #username"
Dim user_id_select As New Integer
Dim searchSQL As New SqlCommand
conn.Open()
searchSQL = New SqlCommand(searchComm, conn)
searchSQL.Parameters.AddWithValue("#username", txtUserSearch.Text)
Dim datareader As SqlDataReader = searchSQL.ExecuteReader()
While datareader.Read
lstUsers.Items.Add(datareader.Item("username"))
End While
datareader.Close()
conn.Close()
Dim conn2 As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim selectComm As String = "SELECT user_id FROM users WHERE username=#username_selected"
Dim selectSQL As New SqlCommand
conn2.Open()
selectSQL = New SqlCommand(selectComm, conn2)
selectSQL.Parameters.AddWithValue("#username_selected", lstUsers.SelectedItem.Text.Trim)
Dim datareader2 As SqlDataReader = selectSQL.ExecuteReader()
While datareader2.Read
If datareader2.HasRows Then
user_id_select = datareader2("user_id")
lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text
ElseIf datareader2.HasRows = False Then
lblInvalidUsername.Visible = True
datareader2.Close()
End If
End While
conn2.Close()
End Sub
Hi,
I'm gettin a NullReference exception on lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text whenever I enter a username in txtUserSearch and click search, it was working previously.. I don't know what happened..
Can anyone tell me whats wrong?
I assume you're getting the NullReferenceException on this line:
selectSQL.Parameters.AddWithValue("#username_selected", lstUsers.SelectedItem.Text.Trim)
since you haven't specified the SelectedItem of the recently filled ListBox. To select the first item you could use this code:
While datareader.Read
lstUsers.Items.Add(datareader.Item("username"))
End While
If lstUsers.Items.Count <> 0 Then lstUsers.SelectedIndex = 0
You are also not handling the case that there are no usernames in the database, then the ListBox is empty and has no selected-item.
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.