Make If Statments Using Gridview LinkButtons - asp.net

I have 2 Linkbuttons inside each row of my gridview.
I want to know how I can use If statements to determine which changes should be made.
My current If statements(which I know are wrong) are as follows:
If LinkButton1.Text = "Update" Then
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
strSelect = "SELECT Classid, Addate, Category, Username, Phonenbr, Email, Description, Fulldescription FROM TABLENAME WHERE Classid = '" & strFilter & "' "
Page.Session.Add("Admin_Updates", strSelect)
Response.Redirect("DispAd.aspx")
ElseIf LinkButton2.Text = "Delete" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
ClassifiedStr.CommandText = "delete_classifieds"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_id", OleDbType.Date).Value = strFilter
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
End if
What do I use in place of my lines If LinkButton1.Text = "Update"
Update:
I added CommandName="UpdateRow" and "DeleteRow" to HTML Linkbutton and did the following:
If LinkButton1.CommandName = "UpdateRow"
and
ElseIf LinkButton2.CommandName = "DeleteRow" Then
However, the Delete one simply Deletes the LinkButton and not the Database record which is weird?! Not sure why.
I also see that the Display button will only work once I click Delete, change page, go back to first page which has Delete Removed. So if Delete is present Display doesn't work.
UPDATED FULL VERSION THAT DOESN'T WORK
VERSION 1
Protected Sub DisplayClassifieds_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DisplayClassifieds.SelectedIndexChanged
Dim conn As OleDbConnection = New OleDbConnection("Provider=""********"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
Dim strSelect As String
Dim strFilter As String = " "
' Dim counter As Integer = 0
' Dim v As Integer = 0
'cell = DisplayClassifieds[0,Row].Value
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
strSelect = "SELECT Classid, Addate, Category, Username, Phonenbr, Email, Description, Fulldescription FROM TABLENAME WHERE Classid = '" & strFilter & "' "
If LinkButton1.commandName = "UpdateRow" Then
Page.Session.Add("Admin_Updates", strSelect)
Response.Redirect("DispAd.aspx")
ElseIf LinkButton2.commandName = "DeleteRow" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandText = "DELETE * FROM TABLENAME WHERE Classid = '" & strFilter & "'"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_id", OleDbType.Date).Value = strFilter
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
Response.Redirect("QRY2.aspx")
End If
End Sub
VERSION 2
Sub LinkButton1_Click(sender As Object, e As EventArgs)
Dim conn As OleDbConnection = New OleDbConnection("Provider=""********"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
Dim strSelect As String
Dim strFilter As String = " "
Dim counter As Integer = 0
Dim v As Integer = 0
'cell = DisplayClassifieds[0,Row].Value
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
strSelect = "SELECT Classid, Addate, Category, Username, Phonenbr, Email, Description, Fulldescription FROM TABLENAME WHERE Classid = '" & strFilter & "' "
Page.Session.Add("Update_Values", strSelect)
Response.Redirect("DispAdUpdate.aspx")
End Sub
Sub LinkButton2_Click(sender As Object, e As EventArgs)
Dim conn As OleDbConnection = New OleDbConnection("Provider=""*******"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
Dim strFilter As String = " "
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
strFilter = row.Cells(1).Text
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
ClassifiedStr.CommandText = "delete_classifieds"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_id", OleDbType.Date).Value = strFilter
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
Response.Redirect("QRY2.aspx")
End Sub

You should put strFilter = row.Cells(1).Text line above if statement (If LinkButton1.Text = "Update" Then).

It looks like doing this process is very hard.
I decided to do a "select" option instead since my question seemed difficult.
I do this like so:
For the select option row:
Protected Sub DisplayClassifieds_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DisplayClassifieds.SelectedIndexChanged
Dim row As GridViewRow = DisplayClassifieds.SelectedRow
End Sub
Then making a delete and update button that takes that index as so....
Protected Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles BtnDelete.Click
Dim conn As OleDbConnection = New OleDbConnection("Provider=""******"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
If Page.IsValid Then
If DisplayClassifieds.SelectedIndex = -1 Then
Response.Write("<script language=""javascript"">alert('You must select a record.');</script>")
Exit Sub
End If
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
ClassifiedStr.CommandText = "delete_classifieds"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
'DataKey is the DataKey that we labeled as Classid(same name as ID field in Oracle)
ClassifiedStr.Parameters.Add("val_id", OleDbType.Numeric).Value = CInt(DisplayClassifieds.SelectedDataKey.Value)
conn.Open()
ClassifiedStr.ExecuteNonQuery()
....etc
The bottom "DataKey" code from my VB.net comes from the table options I made with the use of "DataKeyNames" value :
<asp:GridView ID="DisplayClassifieds" runat="server" align="center"
Width="100%" AllowSorting="True" AutoGenerateColumns="False"
AutoGenerateSelectButton="True" EnableModelValidation="True"
BorderColor="Black" BorderStyle="Solid" DataKeyNames="Classid" >
<Columns>
<asp:BoundField DataField="Classid" HeaderText="ID"
SortExpression="Date" Visible = "false">
<ItemStyle cssClass="grid_padding" />
</asp:BoundField>
....etc
</Columns>
</asp:GridView>

I'm not as familiar with using/calling stored procedures but, if it's not too much of a hassle, try typing your delete query out in the commandtext property, ex.
ElseIf LinkButton2.Text = "Delete" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandText = "DELETE * FROM TABLENAME WHERE val_id = #val_id"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.AddWithValue("#val_id", strFilter)
conn.Open()
ClassifiedStr.ExecuteNonQuery()
conn.Close()
Response.AddHeader("Refresh", "1")
End if
Since I haven't ever called stored procedures I am just guessing that it has something to do with the way you are calling it for delete

Related

VB.net Input string was not in a correct format

Here is a picture of error
Keep Getting error
input string was not in correct format
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
My guess is the CInt but it works in another similar application . Not sure what is going on . Here is the code
product-detail.aspx.vb
Imports System.Data
Imports System.Data.SqlClient
Partial Class HTML_Product_Detail
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("ProductID") <> "" Then
Dim strConn As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
Dim connProduct As SqlConnection
Dim cmdProduct As SqlCommand
Dim drProduct As SqlDataReader
Dim strSQL As String = "Select * from Product Where ProductID = " & Request.QueryString("ProductID")
connProduct = New SqlConnection(strConn)
cmdProduct = New SqlCommand(strSQL, connProduct)
connProduct.Open()
drProduct = cmdProduct.ExecuteReader(CommandBehavior.CloseConnection)
'drProduct.Read()
If drProduct.Read() Then
lblProductName.Text = drProduct.Item("ProductName")
lblProductDescription.Text = drProduct.Item("ProductName")
lblPrice.Text = drProduct.Item("Price")
lblProductNo.Text = drProduct.Item("ProductNo")
imgProduct.ImageUrl = "images/product-detail/" + Trim(drProduct.Item("ProductNo")) + ".jpg"
End If
End If
End Sub
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
' *** get product price
Dim dr As SqlDataReader
Dim strSQLStatement As String
Dim cmdSQL As SqlCommand
Dim strConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
strSQLStatement = "SELECT * FROM Product WHERE ProductNo = '" & lblProductNo.Text & "'"
Dim conn As New SqlConnection(strConnectionString)
conn.Open()
cmdSQL = New SqlCommand(strSQLStatement, conn)
dr = cmdSQL.ExecuteReader()
Dim decPrice As Decimal
If dr.Read() Then
decPrice = dr.Item("Price")
End If
conn.Close()
'*** get CartID
Dim strCartID As String
If HttpContext.Current.Request.Cookies("CartID") Is Nothing Then
strCartID = GetRandomCartIDUsingGUID(10)
Dim CookieTo As New HttpCookie("CartID", strCartID)
HttpContext.Current.Response.AppendCookie(CookieTo)
Else
Dim CookieBack As HttpCookie
CookieBack = HttpContext.Current.Request.Cookies("CartID")
strCartID = CookieBack.Value
End If
'Check if this product already exist in the cart
Dim dr2 As SqlDataReader
Dim strSQLStatement2 As String
Dim cmdSQL2 As SqlCommand
strSQLStatement2 = "SELECT * FROM cart WHERE CartID ='" & strCartID & "' and ProductID = '" & Trim(lblProductNo.Text) & "'"
'Reponse.Write(strSQlStatement2)
Dim conn2 As New SqlConnection(strConnectionString)
cmdSQL2 = New SqlCommand(strSQLStatement2, conn2)
conn2.Open()
dr2 = cmdSQL2.ExecuteReader()
If dr2.Read() Then
Dim intQuantityNew As Integer = dr2.Item("Quantity") + CInt(tbQuantity.Text)
strSQLStatement = ""
cmdSQL = New SqlCommand(strSQLStatement, conn)
Else
Dim dr3 As SqlDataReader
Dim strSQLStatement3 As String
Dim cmdSQL3 As SqlCommand
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
'Response.Write(strSQLStatement3)
Dim conn3 As New SqlConnection(strConnectionString)
conn3.Open()
cmdSQL3 = New SqlCommand(strSQLStatement3, conn3)
dr3 = cmdSQL3.ExecuteReader()
End If
'Response.Redirect("ViewCart.aspx")
End Sub
Public Function GetRandomCartIDUsingGUID(ByVal length As Integer) As String
'Get the GUID
Dim guidResult As String = System.Guid.NewGuid().ToString()
'Remove the hyphens
guidResult = guidResult.Replace("-", String.Empty)
'Make sure length is valid
If length <= 0 OrElse length > guidResult.Length Then
Throw New ArgumentException("Length must be between 1 and " & guidResult.Length)
End If
'Return the first length bytes
Return guidResult.Substring(0, length)
End Function
End Class
The issue is almost certainly here:
CInt(tbQuantity.Text)
The exception information even says:
Conversion from string "" to type 'Integer' is not valid.
You cannot convert a String to an Integer if the text doesn't represent a valid value and an empty string obviously doesn't represent a number. Validate the data first or else validate and convert in one go using Integer.Tryparse.

Query string not retrieving data values

Hope you guys could give me some help.
I have a asp.net web form which gets data from SQL database and displays it on webpage via product code number or product description.
Searching by description will display a list of similar products where each list will have a button with the product code when clicked will open another site with extra product information,
e.g.
13892
14589
17485
00010
08890
The problem is all the codes that start from 1 upwards will show more details, but when I click on product codes that start with 0 such as 00010, 08890 will show no data when in fact there should be data.
Any help would be appreciated.
code I have below,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Val(Request.QueryString("Stock_code")) <> 0 Then
Dim dt As DataTable = New DataTable
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & _
"AND LOC_STOCK_CODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & Val(Request.QueryString("stock_code")) & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & Val(Request.QueryString("stock_code")) & "'"
Using cmd4 As SqlCommand = New SqlCommand(strQuery4)
Dim da3 As SqlDataAdapter = New SqlDataAdapter
Dim dt4 As New DataTable
cmd4.Connection = cnn : cnn.Open()
da3.SelectCommand = cmd4
da3.Fill(dt4)
For i = 0 To dt4.Rows.Count - 1
Label8.Text = dt4.Rows(i).Item("Retail_Rest_Split")
Next
End Using
cnn.Close()
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = cnn : cnn.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
For i = 0 To dt.Rows.Count - 1
Label7.Text = dt.Rows(i).Item("Stock_Code")
Label1.Text = dt.Rows(i).Item("Notes")
Label3.Text = dt.Rows(i).Item("Retail_Price")
Label4.Text = dt.Rows(i).Item("Pack_Size")
Label5.Text = dt.Rows(i).Item("Stock_Description")
'Label8.Text = dt.Rows(i).Item("Pack_Size")
Label9.Text = dt.Rows(i).Item("Net_Weight")
Label10.Text = dt.Rows(i).Item("Gross_Weight")
GridView1.DataSource = dt
GridView1.DataBind()
Next
End Using
cnn.Close()
Dim dt3 As DataTable = New DataTable
Using cmd3 As SqlCommand = New SqlCommand(strQuery3)
Dim da2 As SqlDataAdapter = New SqlDataAdapter
cmd3.Connection = cnn : cnn.Open()
da2.SelectCommand = cmd3
da2.Fill(dt3)
End Using
For i = 0 To dt3.Rows.Count - 1
Label6.Text = dt3.Rows(i).Item("Chinese_Description")
Next
Dim cmd2 As New SqlCommand
Dim dt2 As New DataTable
Dim da As New SqlDataAdapter
With cmd2
.Connection = cnn
.CommandText = strQUery2
End With
da.SelectCommand = cmd2
da.Fill(dt2)
GridView1.DataSource = dt2
GridView1.DataBind()
End If
End Sub
You want to use a paramaterized query like this (I'm going to fold that query string to make it more readable without having to scroll horizontally):
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description],
STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as
[Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as
[Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM
dbo.STK_STOCK WHERE STKCODE = #StockCode"
Using cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#StockCode", Request.QueryString("Stock_code"))
' Do your other stuff here.
End Using
Note, that you don't want to just use string concatenation to insert your query parameter. That opens you up to SQL injection attacks.
Instead, you use a placeholder in your query like #StockCode. Then you call AddWithValue on the command to give it the value of that parameter.
You can also explicitly specify the parameter type if you need to:
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
Assuming they are all 5 digit codes, this will make sure the stock code is numeric.
Replace
Val(Request.QueryString("Stock_code"))
with
String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Will raise an exception if Request.QueryString("Stock_code") is not parsed as integer, which prevents against malicious injection.
For example:
Dim stockCode = String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & stockCode & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & "AND LOC_STOCK_CODE = '" & stockCode & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & stockCode & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & stockCode & "'"
#dwilliss has just answered the question using parameters, which is probably better than my method. Posting this anyway

GridViewUpdateEventArgs not working with update to sql table

I'm not getting my GridViewUpdateEventArgs to work for some reason.
I'm trying to update my gridview(table in sql) but it´s not working.
And i don´t know how to write the the Where clause in the sql to match.
Public Sub GridView1_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Dim SelectRow As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim RowID As HiddenField = Gridview1.FindControl("ID")
Dim Report As String = SelectRow.Cells(1).Text
Dim BusinessArea As String = SelectRow.Cells(2).Text
Dim Salesdepartment As String = SelectRow.Cells(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim SqlCommand As New SqlCommand("UPDATE TEST SET Report = ('" & Report & "'), [Business Area] = ('" & BusinessArea & "'), Salesdepartment = ('" & Salesdepartment & "') WHERE ID = #RowID ", SqlConnection)
Dim SqlDataAdapter As New SqlDataAdapter(SqlCommand)
Dim dataSet As New DataSet()
SqlDataAdapter.Fill(dataSet)
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using
The "ID" column is my PK in the table and is in a (ItemTemplate) (Hidden)
In this Way SqlDataAdapter can't update database record, see here how to update record using SqlDataAdapter .
or you can try like this:
Dim row As GridViewRow = Gridview1.Rows(e.RowIndex)
Dim hf As HiddenField = TryCast(row.FindControl("ID"), HiddenField)
Dim Report As [String] = row.Cell(1).Text
Dim BusinessArea As [String] = row.Cell(2).Text
Dim Salesdepartment As [String] = row.Cell(3).Text
Using SqlConnection As New SqlConnection(SqlConnectionString)
SqlConnection.Open()
Dim cmd As New SqlCommand("UPDATE TEST SET Report = #Report,[Business Area] =#BusinessArea, Salesdepartment=#Salesdepartment WHERE ID = #RowID ", SqlConnection)
cmd.Parameters.AddWithValue("#Report", Report)
cmd.Parameters.AddWithValue("#BusinessArea", BusinessArea)
cmd.Parameters.AddWithValue("#Salesdepartment", Salesdepartment)
cmd.Parameters.AddWithValue("#RowID", hf.Value)
cmd.ExecuteNonQuery()
Gridview1.EditIndex = -1
BindDataToGridView()
SqlConnection.Close()
End Using

database cannot update textbox value in vb.net

I am doing a update profile in a web application using vb.net. At first I read the database and put the data into the textbox, then i change the data inside the textbox and click the 'update' button. The problem is when i click the button, it won't update the latest value that i typed into the textbox. It will still update the value where i read from database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim item1 As String = CType(Session.Item("UserAccount"), String)
txtUsername.Enabled = False
conn.Open()
sql1 = "Select * From [Users] WHERE username='" & item1 & "'"
cmd = New SqlCommand(sql1, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
txtUsername.Text = dr.Item("username")
password = dr.Item("password")
txtFirstName.Text = dr.Item("firstname")
txtLastName.Text = dr.Item("lastname")
txtDob.Text = dr.Item("dob")
txtEmail.Text = dr.Item("email")
txtNumber.Text = dr.Item("phone")
txtAddress.Text = dr.Item("address")
End If
dr.Close()
conn.Close()
End Sub
'above this image is how i read from the database.
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim errFirstName As Boolean = True
Dim errLastName As Boolean = True
Dim errCPassword As Boolean = True
Dim errNPassword As Boolean = True
Dim errDob As Boolean = True
Dim errEmail As Boolean = True
Dim errNumber As Boolean = True
Dim errAddress As Boolean = True
Dim newFName, newLName, newPassword, newAddress, newNumber, newEmail, newDob As String
If txtFirstName.Text = "" Then
txtFirstName.BackColor = Drawing.Color.LightPink
lblFirstName.Text = "cannot be empty"
ElseIf Not Regex.Match(txtFirstName.Text, "^[a-zA-Z_ ]*$", RegexOptions.IgnoreCase).Success Then
.
.
.
This is the 'Update' button click.
Here is where i do all the validation for the value in textbox
If errNPassword = False And errCPassword = False And errFirstName = False And errLastName = False And errDob = False And errEmail = False And errNumber = False And errAddress = False Then
conn.Open()
sql2 = "Update [Users] Set password='" & newPassword & "', firstname='" & newFName & "', lastname='" & newLName & "', dob='" & newDob & "', address='" & newAddress & "', email='" & newEmail & "', phone='" & newNumber & "' WHERE username='" & txtUsername.Text & "'"
cmd = New SqlCommand(sql2, conn)
cmd.ExecuteNonQuery()
conn.Close()
Response.Redirect(String.Format("~/index.aspx?"))
Else
Dim message As String = "Please correct the error above"
Dim sb As New System.Text.StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("window.onload=function(){")
sb.Append("alert('")
sb.Append(message)
sb.Append("')};")
sb.Append("</script>")
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb.ToString())
Exit Sub 'break
End If
This is how i update the value of textbox to my database where the username is match.
Your page is posting back and running the same code, you have to add If Not IsPostBack to Page_Load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack
Dim item1 As String = CType(Session.Item("UserAccount"), String)
txtUsername.Enabled = False
conn.Open()
sql1 = "Select * From [Users] WHERE username='" & item1 & "'"
cmd = New SqlCommand(sql1, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
txtUsername.Text = dr.Item("username")
password = dr.Item("password")
txtFirstName.Text = dr.Item("firstname")
txtLastName.Text = dr.Item("lastname")
txtDob.Text = dr.Item("dob")
txtEmail.Text = dr.Item("email")
txtNumber.Text = dr.Item("phone")
txtAddress.Text = dr.Item("address")
End If
dr.Close()
conn.Close()
End If
End Sub

Unclosed quotation mark after the character string - What's wrong with this MSSQL query?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
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 * FROM Table1 WHERE Date =" & TextBox1.Text & "'", SQLData)
SQLData.Open()
Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
While dtrReader.Read()
For j As Integer = 1 To 31
Dim s As String = "s" & j
If dtrReader(s.ToString()).ToString() = "b" Then
Dim img As ImageButton = DirectCast(Panel1.FindControl(s.ToString()), ImageButton)
img.ImageUrl = "~/Images/booked.gif"
img.Enabled = False
End If
Next
End While
dtrReader.Close()
SQLData.Close()
End Sub
Error:
Unclosed quotation mark after the character string ''.
I think you should add another "'" before the date.
# Line 3 after TextBox1.Text &
Also, I would highly recommend you to validate the date string from the textbox, here is an abstract example, not tested:
Dim input = TextBox1.Text
Dim dateVal As Date
Dim sqlDate As String
If Not Date.TryParse(input, dateVal) Then
Throw New FormatException("Input date was invalid.")
Else
Try
sqlDate = New SqlDateTime(dateVal).ToSqlString
Catch ex As Exception
Throw New FormatException("Input date was invalid.")
End Try
End If
Dim query = "SELECT * FROM Table1 WHERE Date = '" & sqlDate & "'"
If you want to compare only by years, months etc., it's very essential you should read this post as well.
I think it should be:
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT * FROM Table1 WHERE Date ='" & TextBox1.Text & "'", SQLData)
I just added a ' after Date =.
But remember this is not a great way to build the query and makes the code prone to SQL Injection.
Try the following:
...
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT * FROM Table1 WHERE Date = #Date", SQLData)
cmdSelect.Parameters.Add(New System.Data.SqlClient.SqlParameter("#Date", TextBox1.Text))
...

Resources