Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SQLData As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM Table1 WHERE Name =" + TextBox1.Text + " And Last = '" + TextBox2.Text + "'", SQLData)
SQLData.Open()
If cmdSelect.ExecuteScalar > 0 Then
Label1.Text = "Record Found ! " & TextBox1.Text & " " & TextBox2.Text
Return
End If
Label1.Text = "Record Not Found ! "
SQLData.Close()
End Sub
I write this code to find whether the record entered in textbox1 and textbox2 exists or not ..if record exist ..then in label1 the text would be RECORD FOUND else NO RECORD FOUND
ERROR :
**when i enter in textbox1 and textbox2 then on button click event it shows the error : Invalid column name ,,**
Please use SqlCommand.Parameters collection. Please!! For the sake of better programming.
Dim cmdSelect As New System.Data.SqlClient.SqlCommand(
"SELECT COUNT(*) FROM Table1 WHERE Name = #Name And Last = #Last", SQLData)
cmdSelect.Parameters.AddWithValue("#Name",TextBox1.Text)
cmdSelect.Parameters.AddWithValue("#Last",TextBox2.Text)
TextBox1.Text should be passed inside single quotes (').
Beside that, it seems to be another Little Bobby Tables case.
You need to add ' around the Textbox1.text value
e.g
'" + TextBox1.Text + "'
You should really not doing it like this since this is open for sql injection. Except from that I think you are missing some ' in the query around TextBox1.Text.
Related
Good day All
i have an issue with connection string
I'm getting this exception
The ConnectionString property has not been initialized.
on the RowDataBound of the outer gridview sub routine (VB.NET)
when trying to bind data to inner gridview
the code:
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As SqlDataSource
Dim strQRY As String = ""
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
strQRY = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
'Initialize command object
Dim cmd As New SqlCommand(strQRY, conn)
Dim dsTemp As New SqlDataSource()
dsTemp.SelectCommand = strQRY
Return dsTemp
End Using
End Function
This event occurs for each row
Protected Sub gvOdv_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim connString As String = ConfigurationManager.ConnectionStrings("MoyensAeriensConnectionString").ConnectionString
Dim conn As New SqlConnection(connString)
conn.Open()
Dim row As GridViewRow = e.Row
Dim strSort As String = String.Empty
' Make sure we aren't in header/footer rows
If row.DataItem Is Nothing Then
Return
End If
'Find Child GridView control
Dim gv As New GridView()
gv = DirectCast(row.FindControl("gvSorties"), GridView)
'Check if any additional conditions (Paging, Sorting, Editing, etc) to be applied on child GridView
If gv.UniqueID = gvUniqueID Then
gv.PageIndex = gvNewPageIndex
gv.EditIndex = gvEditIndex
'Check if Sorting used
If gvSortExpr <> String.Empty Then
GetSortDirection()
strSort = " ORDER BY " & String.Format("{0} {1}", gvSortExpr, gvSortDir)
End If
'Expand the Child grid
ClientScript.RegisterStartupScript([GetType](), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" & DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString() & "','one');</script>")
End If
'Prepare the query for Child GridView by passing the Odv ID of the parent row
gv.DataSource = ChildDataSource(DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString(), strSort)
gv.DataBind()
'Add delete confirmation message for Customer
Dim l As LinkButton = DirectCast(e.Row.FindControl("linkDeleteCust"), LinkButton)
l.Attributes.Add("onclick", "javascript:return " & "confirm('Are you sure you want to delete this Customer " & DataBinder.Eval(e.Row.DataItem, "OdvID") & "')")
End Sub
thanks (I'v been hunting this error for last 3 hours)
It looks like both code snippets use a separate connection string. ChildDataSource uses "SiteConnectionString" and gvOdv_RowDataBound uses "MoyensAeriensConnectionString", hopefully I'm not pointing out the obvious here, but if so, are both of those present in your config file?
When you have created the SqlDataSource dynamically in your first code snippet, You haven't set its ConnectionString property, that's why this error is coming up.
Note that you also haven't assigned any ID to your SqlDataSource. Its better to do this too.
You also need to set the ConnectionString property of SqlDataSource.
Dim dsTemp As New SqlDataSource()
dsTemp.ID = "mySqlSourceControl"
dsTemp.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionStr").ConnectionString
dsTemp.SelectCommand = strQRY
...
Rest of things should also be fine like: web.config has a connection string for the key mentioned [ e.g. ConnectionStr here]
Instead of returning a SQLDataSource as the gridview's datasource, perhaps return a dataset.
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As DataSet
Dim strQRY As String = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
Using da As New SqlDataAdapter(strQRY, conn)
Using ds As New DataSet
If da.Fill(ds) > 0 Then
Return ds
Else
Return New DataSet
End If
End Using
End Using
End Using
End Function
The method to set the datasource of the child gridview remains the same.
this code works fine but its inserts the same data twice in sql db on just one button click . if i made some mistake plz let me know ..
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As New SqlCommand
Dim str As String
str = "insert into cmember(name,period,design,duty,quali,cont)values ('" & TextBox1.Text & "', '" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "', '" & TextBox5.Text & "','" & TextBox6.Text & "')"
If con.State = ConnectionState.Closed Then
con.Open()
End If
Try
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.CommandText = str
Catch ex As Exception
MsgBox(e.ToString)
End Try
If cmd.ExecuteNonQuery Then
Label1.Text = "entry saved"
con.Close()
Else
Label1.Text = "entry not saved"
End If
End Sub
I can't see the valid reason why it inserts twice a same record in current code snippet. May be a button is hit twice or you are refreshing a web page.
Off-the topic : Do not use hard coded SQL statement. Use parameterized query. (Read about SQL Injection)
str = "insert into cmember (name,period,design,duty,quali,cont) values
(#name,#period,#design,#duty,#quali,#cont)"
This might seem silly, but you're not double clicking the button, are you ?
Also, never use a Msgbox call in ASP - the messagebox will appear on the server, not on the browser, and it will block the thread until clicked. You're much better to create an ASP Label control and assign the text to that.
Also, the bit enclosed in a Try block is just settings and will never throw an error - the try block should be around the commands where you open the connection, and where you execute the query.
Your code is not appearing to insert this data in twice.
The best way to find out what exactly is happening is to run a trace through SQL Server Profiler. To do this you need to ensure you have ALTER TRACE permissions on the instance.
This code is intended to grab the ID of the deleted record, the user who deleted the record, and the date and time the record was deleted and insert it into a hostical table.
So far, once a record is deleted, the code grabs more than one deleted record.
Please see my code and what I am doing wrong.
Thanks alot in advance for your help.
Protected Sub GridView1_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles GridView1.RowDeleted
Dim connStr As String = ConfigurationManager.ConnectionStrings("Constr").ConnectionString
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String = ""
' Indicate whether the delete operation succeeded.
If e.Exception Is Nothing Then
Dim strID As String = GridView1.FindControl("ID").Cells(1).Text
'Who deleted a record?
sql += "Insert into Archives ([ID],[choice],[date_stamp],[approved],[chcknum],[DeletedBy],[dateDeleted]) "
sql += " SELECT [ID],[choice],[date_stamp],[approved],[chcknum],[login],getDate() from Depends "
sql += " inner join Emp on Depends.employee_id = Emp.employee_id where login ='" & Session.Item("UserName").ToString & "' and upass = '" & Session.Item("Password").ToString & "' and [ID] = '" & strID & "' "
End If
Response.Write(sql)
Response.End()
Try
cnn = New SqlConnection(connStr)
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
sql = ""
Catch ex As SqlException
Dim errorMsg As String = "Error in Updation"
errorMsg += ex.Message
Throw New Exception(errorMsg)
Finally
cnn.Close()
End Try
End Sub
My problem, I think, lies in this line of code:
Dim strID As String = GridView1.FindControl("ID").Cells(1).Text
I don't think it is correct.
I'm guessing you're looking for the GridView.DataKeys property. Use it to tell your GridView which column(s) in the data is should use as an unique identifer.
You probably also want to look into a few other optimzations for your code:
Use parameters in your query, don't concatenate a SQL statement like that.
Use the Using statement with your SqlConnection and SqlCommand objects for proper and easy disposal.
You're not achiving anything with the try-catch, in fact you're obscuring the exception stack.
Update:
See the GridViewDeletedEventArgs.Keys Property to get the ID of the deleted row. Is the "ID" column part of the query you're using to bind the GridView?
Here's a better (complete) example:
.aspx:
<asp:GridView ID="GridView1" DataKeyNames="ID" AutoGenerateDeleteButton="true" runat="server">
</asp:GridView>
Code-behind, with some dummy data:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim x() = {New With {.id = 1, .name = "xxx"}, New With {.id = 2, .name = "zzz"}}
GridView1.DataSource = x
GridView1.DataBind()
End If
End Sub
Private Sub GridView1_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
Dim id As Integer = CInt(e.Keys(0))
' Do your stuff!
' Don't forget to rebind the GridView, it will still have the deleted row in Viewstate.
End Sub
End Class
If you are running SQL Server, It might be easier to use a delete trigger on the table.
http://msdn.microsoft.com/en-us/library/aa258254%28v=SQL.80%29.aspx
...deleted and inserted are logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is attempted, and hold the old values or new values of the rows that may be changed by the user action.
What is wrong with my this code, i think the select query is wrong :
i have a textbox1, textbox2 and textbox3
when i type employee id in textbox1 and Email in textbox2 then in textbox3 the password will be retrieved according to employee id and email in database...
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
'Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT Password FROM a1_admins WHERE EmployeeId" = TextBox1.Text And "Email" = TextBox2.Text, SQLData)
Dim SQLData As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True")
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT Password FROM a1_admins WHERE EmployeeId =" & TextBox1.Text & "And" & "Email" = TextBox2.Text, SQLData)
SQLData.Open()
Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
If dtrReader.HasRows Then
While dtrReader.Read()
TextBox3.Text = dtrReader("Password")
End While
Else
TextBox3.Text = ("No customer found for the supplied ID.")
End If
dtrReader.Close()
SQLData.Close()
End Sub
Why not giving your controls proper names?
Never ever build your query string by string concatination, use SqlParameter instead (Especially in a ASP.NET application!), to avoid sql injection.
Maybe you want to use HttpServerUtility.HtmlDecode too, to avoid injection of javascript and other nasty stuff on postback.
Use usings for disposable objects like SqlConnection and SqlDataReader
Yeah its definitely your SQL. There have to be syntax errors, because the query string is not concatenate correctly.
You haven't got quotes around the values, nor added any extra whitespace.
Really your query should have parameters in:
SELECT Password FROM a1_admins WHERE EmployeeId = #employeeID And Email = #email
It would have been useful if you had posted the actual error message.
However, I think your SQL query is missing some spaces. It should be:
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT Password FROM a1_admins WHERE EmployeeId = " & TextBox1.Text & " And " & "Email = '" & TextBox2.Text & "'", SQLData)
Edit
As pointed out in other answers you should really be using parameters. I have provided a link to the MSDN article on using Parameters with the SQLCommand class
Try this (note the quotes) - assuming that EmloyeeId is an int and Email is some kind of varchar
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT Password FROM a1_admins WHERE EmployeeId =" & TextBox1.Text & " And Email = '" & TextBox2.Text & "'", SQLData)
I want to populate the dropdownlist ddVerantwortlich1 with the people with the proper credentials based on the selected process step ddProzessschritt1
It doesn't work if I want to change it using datasource and databind
i have to manually loop through the table in the dataset returned from the query. then it works. but not otherwise...
What's the problem? Here my code:
Protected Sub ddProzessschritt1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddProzessschritt1.SelectedIndexChanged
'StefanSteiger.Debug.MsgBox("index changed!")
Dim dsProcessResponsibleDataSet As Data.DataSet = New DataSet
Dim strSQL As String = "SELECT BE_ID, (BE_Name + ' ' +BE_Vorname) as UserName FROM T_Benutzer WHERE BE_ID IN "
strSQL += "(SELECT BEBG_BE FROM T_Benutzer_Benutzergruppen WHERE BEBG_BG IN "
strSQL += "(SELECT ZO_BG_ID FROM T_DMS_ZO_Prozesse_Berechtigungen WHERE ZO_PROC_UID = '" + ddProzessschritt1.SelectedValue.ToString + "')) ORDER BY UserName"
If StefanSteiger.DBcmds.GetDataSet(strSQL, dsProcessResponsibleDataSet) > 0 Then
Me.ddVerantwortlich1.Items.Clear()
For Each row As Data.DataRow In dsProcessResponsibleDataSet.Tables(0).Rows
'StefanSteiger.Debug.MsgBox(row("UserName").ToString + " ¦ " + row("BE_ID").ToString)
ddVerantwortlich1.Items.Add(New ListItem(row("UserName"), row("BE_ID")))
Next
'Me.ddVerantwortlich1.Dispose()
'Me.ddProzessschritt1.DataSource = dsProcessResponsibleDataSet.Tables(0)
'Me.ddVerantwortlich1.DataTextField = "UserName"
'Me.ddVerantwortlich1.DataValueField = "BE_ID"
'Me.ddVerantwortlich1.DataBind()
Else
'Me.ddProzessschritt1.Dispose()
ddVerantwortlich1.Items.Add(New ListItem("Niemand verantwortlich.", Nothing))
End If
End Sub
Why you call Dispose on the DropDown? Maybe that's the problem. Give it a try!