GridViewUpdateEventArgs not working with update to sql table - asp.net

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

Related

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

Using ViewState to apply filters on Listview

I have used ListView Control to gets list of products from database. I also stores result in viewstate . Now to apply filter from checkbox to get refined data I want to know how can I use viewState values?
e.g. If 10 Products found in Music category when page loads. Now if user apply filter(Bluetooth) then only that products should be shown which are in Music & has bluetooth..
Now It is working Like on page load Music category gets fetched Then if I check Bluetooth filter then all bluetooth products comes which are not related to music.
Private Sub shop_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim pageName As String = Me.Page.RouteData.Values("category").ToString()
if not Me.isPostback Then
Try
query = select * from products where category = '"+pageName+"'
Dim conString As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Dim con As New MySqlConnection(conString)
Dim cmd As New MySqlCommand(query)
con.Open()
Dim da As New MySqlDataAdapter()
cmd.Connection = con
da.SelectCommand = cmd
Dim dt As New DataTable()
da.Fill(dt)
ViewState("Data") = dt
products.DataSource = dt
products.DataBind()
catHeading.Text = pageName
itemCount.Text = dt.Rows.Count.ToString
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End Sub
Filter Apply code
Private Sub priceFilter_SelectedIndexChanged(sender As Object, e As EventArgs) Handles priceFilter.SelectedIndexChanged
'buildWhereClause()
Dim price As String = priceFilter.SelectedValue.ToString()
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.[Select]((Convert.ToString("category='") & price) + "'")
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Sub
I just want when user apply any filter then it should check from viewstate(Data) rather to entire table.
Save your category in viewstate & on Checked get that category in string & join that string in your query. something like this
Dim constr As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString
Dim query As String = "select * from table"
Dim joiner As String = ""
Dim condition As String = String.Empty
Dim whereClause As String = String.Empty
Dim priceCondition As String = String.Empty
Try
Dim category As String = ViewState("Data")
condition = String.Concat(condition, joiner, String.Format("{0}", category))
If joiner = "" Then joiner = ""
joiner = " where "
If Not String.IsNullOrEmpty(condition) Then
whereClause = String.Concat(whereClause, joiner, String.Format("category Like '%{0}%'", condition))
joiner = " and "
End If
'Same way you can apply multiple filters as you want & then get that in one string like below
Dim masterClause As String = String.Empty
masterClause = (query & whereClause)
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand(masterClause)
Using sda As New MySqlDataAdapter(cmd)
cmd.Connection = con
Using dt As New DataTable()
sda.Fill(dt)
products.DataSource = dt
products.DataBind()
itemCount.Text = dt.Rows.Count.ToString
End Using
End Using
End Using
End Using
For your filter you could use :
Dim dt As DataTable = DirectCast(ViewState("Data"), DataTable)
Dim dr As DataRow() = dt.Select("category='" & category & "'")
products.DataSource = dr
products.DataBind()
itemCount.Text = dr.Length

vb.net OleDbDataAdapter not working with Select From Where

If I Debug this I just get a Invalid Columnname Error("Name of the Object"). I am using a SQL database.
Protected Sub ddlKunden_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlKunden.SelectedIndexChanged
Dim strSql As String
Dim kontakt As String = ddlKunden.SelectedItem.Value
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.ConnectionString = strConnection
connection.Open()
'Kontaktpersonen laden
strSql = "SELECT * FROM Kontaktpersonen WHERE Nr =" & Chr(34) & kontakt & Chr(34)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbP)
End Using
ddlKontaktperson.Items.Clear()
ddlKontaktperson.DataSource = dtbP
ddlKontaktperson.DataTextField = "AP_Nam"
ddlKontaktperson.DataValueField = "ID"
ddlKontaktperson.DataBind()
End Using
ddlKontaktperson.Visible = True
End Sub
The Error pops at
dad.fill(dtbP)
It should select all rows Where Nr="SELECTED VALUE" and you select it in a dropdownlist. And all these rows should be saved in a Datatable then and are used in another dropdownlist.
It works when I try the exact same thing without the where.
Example:
'Kunden laden
strSql = "SELECT * FROM Kontakte"
dtbK = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbK)
End Using
ddlKunden.Items.Clear()
ddlKunden.DataSource = dtbK
ddlKunden.DataTextField = "Nr"
ddlKunden.DataValueField = "Nr"
ddlKunden.DataBind()
Please try following code
You do not need to use "'" around parameters
Just add these values as a parameter to the oledbcommand with its value and type
Otherwise, your sql command will be vulnerable to sql injection
Dim strConnection As String = "Provider=sqloledb;Data Source=(local);" &
"Initial Catalog=kodyaz;" &
"User Id=sa;Password=sa"
Dim kontakt As Int32 = 1
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.Open()
Dim cmd As New OleDbCommand()
cmd.Connection = connection
cmd.CommandText = "SELECT * FROM Kontaktpersonen WHERE Nr = ?"
cmd.Parameters.AddWithValue("Nr", kontakt)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(cmd)
dad.Fill(dtbP)
End Using
End Using

Make If Statments Using Gridview LinkButtons

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

ASP.NET/VB.NET/SQL Server 2012 - Page keeps loading

I'm trying to run this code, and whenever I press the 'Register' button, nothing is happening (the page is like loading but stays on the same page)
Code:
Public Sub register()
Dim Username As String = txtUsername.Text
Dim Surname As String = txtSurname.Text
Dim Password As String = txtPassword.Text
Dim Name As String = txtName.Text
Dim Address1 As String = txtAddress1.Text
Dim Address2 As String = txtAddress2.Text
Dim City As String = txtCity.Text
Dim Email As String = txtEmail.Text
Dim Country As String = drpCountry.Text
Dim DOB As Date = calDOB.SelectedDate
Dim Occupation As String = txtOccupation.Text
Dim WorkLocation As String = txtWorkLocation.Text
Dim Age As Integer = Date.Today.Year - calDOB.SelectedDate.Year
Dim ProjectManager As String = "N/A"
Dim TeamLeader As String = "N/A"
Dim TeamLeaderID As Integer = "1"
Dim ProjectManagerID As Integer = "1"
Dim RegistrationDate As Date = DateTime.Today
Dim ContractType As String = "N/A"
Dim ContractDuration As Integer = 6
Dim Department As String = "N/A"
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim registerSQL As SqlCommand
Dim sqlComm As String
Dim validateSQL As SqlCommand
Dim sqlValidate As String
sqlValidate = "SELECT * FROM users where username=" + txtUsername.Text.ToString
sqlComm = "INSERT INTO users(Username, Password, Name, Surname, Address1, Address2, " +
"City, Country, date_of_birth, age, Occupation, department, work_location, " +
"project_manager,team_leader, team_leader_id, project_manager_id, " +
"date_registration, contract_type, contract_duration) " +
"VALUES(#p1, #p2,#p3,#p4,#p5,#p6,#p7,#p8,#p9,#p10,#p11,#p12,#p13,#p14,#p15," +
"#p16,#p17,#p18,#p19,#p20)"
conn.Open()
validateSQL = New SqlCommand(sqlValidate, conn)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
If dr.HasRows = False Then
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.CommandText = sqlValidate
Dim reader As SqlDataReader = validateSQL.ExecuteReader()
reader.Read()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("#p1", Username)
registerSQL.Parameters.AddWithValue("#p2", Password)
registerSQL.Parameters.AddWithValue("#p3", Name)
registerSQL.Parameters.AddWithValue("#p4", Surname)
registerSQL.Parameters.AddWithValue("#p5", Address1)
registerSQL.Parameters.AddWithValue("#p6", Address2)
registerSQL.Parameters.AddWithValue("#p7", City)
registerSQL.Parameters.AddWithValue("#p8", Country)
registerSQL.Parameters.AddWithValue("#p9", DOB)
registerSQL.Parameters.AddWithValue("#p10", Age)
registerSQL.Parameters.AddWithValue("#p11", Occupation)
registerSQL.Parameters.AddWithValue("#p12", Department)
registerSQL.Parameters.AddWithValue("#p13", WorkLocation)
registerSQL.Parameters.AddWithValue("#p14", ProjectManager)
registerSQL.Parameters.AddWithValue("#p15", TeamLeader)
registerSQL.Parameters.AddWithValue("#p16", TeamLeaderID)
registerSQL.Parameters.AddWithValue("#p17", ProjectManagerID)
registerSQL.Parameters.AddWithValue("#p18", RegistrationDate)
registerSQL.Parameters.AddWithValue("#p19", ContractType)
registerSQL.Parameters.AddWithValue("#p20", ContractDuration)
registerSQL.ExecuteNonQuery()
conn.Close()
ElseIf dr.HasRows = True Then
lblUsername.Text = "That Username (" + txtUsername.Text + ") is already registered/taken."
lblUsername.Visible = True
conn.Close()
End If
End Sub
Button event handler:
Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
register()
End Sub
Is something wrong with the code?
From MSDN
While the SqlDataReader is being used, the associated SqlConnection is
busy serving the SqlDataReader, and no other operations can be
performed on the SqlConnection other than closing it. This is the case
until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
It appears that you have the SqlDataReader open when you try to execute the insert command.
I will try to close it before using the insert command
If dr.HasRows = False Then
dr.Close()
' The following lines are probably a remainder of a copy/paste operation'
' They are not needed and you should remove them'
'validateSQL = New SqlCommand(sqlValidate, conn)'
'validateSQL.CommandText = sqlValidate'
'Dim reader As SqlDataReader = validateSQL.ExecuteReader()'
'reader.Read()'
' Now execute the insert command
Also your command to check for the user presence, apart from perfomance arguments, is wrong because introduces Sql Injection possibilities.
Summarizing try with these changes....
sqlValidate = "SELECT * FROM users where username=#uname"
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.Parameters.AddWithValue("#uname", txtUserName.Text)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
Dim userFound = dr.HasRows
dr.Close()
if userFound = False then
......

Resources