advanced search page for web application using vb.net - asp.net

i created a simple advanced search page for web application, i thought sharing it with you might help beginners
the following is an example of an advanced search page for an employee database using VB.Net
the following is the code behind page
Imports System.Data.OleDb
Partial Class searchme
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim mydb As New OleDbConnection
mydb = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |datadirectory|employee.mdb;Persist Security Info=True")
mydb.Open()
Dim sqlstring = "select * from [dataview] where "
If MRNTextBox1.Text <> "" Then sqlstring = sqlstring + "[code] like '%" + CodeNameTextBox1.Text + "%' OR [EmployeeName] like '%" + CodeNameTextBox1.Text + "%' AND "
If GOVDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Governorate] ='" + GOVDDL.SelectedItem.Text + "' AND "
If genderddl.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Gender] ='" + genderddl.SelectedItem.Text + "' AND "
If DateEmploymentFrom.Text <> "" And DateEmploymentTo.Text <> "" Then sqlstring = sqlstring + "[DateEmployment] >= #" + DatumKonvert1.DK1(DateEmploymentFrom.Text) + "# AND [Datepresentation] <= #" + DatumKonvert1.DK1(DateEmploymentTo.Text) + "# AND "
If DepartmentDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Department] ='" + DepartmentDDL.SelectedItem.Text + "' AND "
sqlstring = Left(sqlstring, Len(sqlstring) - 5) + " order by " + OrderByDDL.SelectedItem.Text
Dim myds As New AccessDataSource
myds.DataFile = "~\App_Data\employee.mdb"
myds.SelectCommand = sqlstring
' Dim Mygrid As New GridView
Mygrid.DataSource = myds
Mygrid.DataBind()
' Me.form1.Controls.Add(Mygrid)
mydb.Close()
RecCount.Text = "Filtered Record Count = " + mygrid.Rows.Count.ToString
Session("dsource") = myds
Response.Redirect("sresults.aspx")
End Sub
End Class

you did a good job, also try the following
link text
link text

Related

Get checkbx values selected from database

I have users form in which they can select some values from checkbox list & values selected in that stores in database in li form. Now I want when users wants to update their form they should be able to see the values checked they have selected earlier.
here is my code.
Insert Form
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
selectedServices &= "<li>" + chk.Text + "</li>"
End If
Next
Try
Dim str1 As String = "INSERT INTO hospitals (`hospitalID`,`username`, `password`) values ('" + ID + "', '"selectedServices.ToString + "', '" + mobileNumber + "', '" + membersAutoPassword.Text + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
On User Profile page after login they should be able to see what options they have selected. Hence there is a option for users to update their details again
UPDATED
User Profile Page
Private Sub list_business_hospital_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Try
Dim str As String = "SELECT * FROM hospitals WHERE username='" + Server.HtmlEncode(Request.Cookies("chkusername").Value) + "';"
con.Open()
Dim cmd As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
Dim lblservice As New Label
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
lblservice.Text = String.Concat(lblservice.Text + ",", chk.Value)
End If
Next
da.Fill(dt)
con.Close()
TextId.Text = dt.Rows(0)("hospitalID").ToString
Catch ex As Exception
Response.Write(ex)
End Try
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Private Sub updateInfo_Click(sender As Object, e As EventArgs) Handles updateInfo.Click
Try
Dim con As New MySqlConnection
Dim query As New MySqlCommand
con.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
query.Connection = con
con.Open()
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If selectedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.Selected = True
End If
Next
query.CommandText = "UPDATE hospitals SET name = '" + businessName.Text + "', contactPerson = '" + contactPerson.Text + "', websiteName = '" + websiteName.Text + "', email = '" + emailName.Text + "', phone1 = '" + phone1.Text + "', phone2 = '" + phone2.Text + "', mobileNumber = '" + mobile.Text + "', buildingName = '" + buildingName.Text + "', streetName = '" + address.Text + "', landmark = '" + landmark.Text + "', areaName = '" + areaName.Text + "', city = '" + suburb.Text + "', state = '" + state.Text + "', zipCode = '" + zip.Text + "', overview = '" + overview.Text + "', registration = '" + regNo.Text + "', establishment = '" + foundation.Text + "', founder = '" + founderName.Text + "', generalBed = '" + GeneralBeds.Text + "', icuBed = '" + ICU.Text + "', consultancyFees = '" + consultinfees.Text + "', mondayFrom = '" + mondayFrom.Text + "', mondayTo = '" + mondayTo.Text + "', tuesdayFrom = '" + tuesdayFrom.Text + "', tuesdayTo = '" + tuesdayTo.Text + "', wednesdayFrom = '" + wedFrom.Text + "', wednesdayTo = '" + wedTo.Text + "', thursdayFrom = '" + thursdayFrom.Text + "', thursdayTo = '" + thursdayTo.Text + "', fridayFrom = '" + fridayFrom.Text + "', fridayTo = '" + fridayTo.Text + "', saturdayFrom = '" + saturdayFrom.Text + "', saturdayTo = '" + saturdayTo.Text + "', sundayFrom = '" + sundayFrom.Text + "', sundayTo = '" + sundayTo.Text + "', visitFrom = '" + visitFrom.Text + "', visitTo = '" + visitTo.Text + "', bestKnownFor = '" + bestknowFor.Text + "' WHERE hospitalID = '" + TextId.Text + "'"
query.ExecuteNonQuery()
con.Close()
Response.Write("<script language='javascript'>alert('Information updated successfully.');</script>")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Please check below,
'Here I assume that, you will call PopulateServices to populate servicesList checkbox list
PopulateServices()
'You didn't mention fieldName, so I assume that field in database is :
'savedServices - This will be li tags like, <li>item 1</li><li>item 2</li>
'Now loop through all items within checkbox list
For Each chk As ListItem In servicesList.Items
'You need to check whether this item saved in database or not?
'If item already saved in database, display as selected
If savedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.selected = true
End If
Next

VB.Net GridView Table with paging, on PageIndexChanging event displays nothing or first page again

I am trying to display data queried from Oracle in a grid view and have added paging with a PageIndexChanging event. However, after a few different tries with small changes, clicking another page either displays screen with no grid view or just refreshes site with gridview still on page 1. Never worked with web apps/sites before, any ideas?
Code:
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Search_Click(sender As Object, e As EventArgs) Handles Search.Click
Dim con As OleDb.OleDbConnection
Dim command As OleDb.OleDbCommand
Dim commandstr As String
Dim wherestr As String
Dim dt As DataTable = New DataTable
Dim oda As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
'Remove any non-aplhanumeric characters from the input string
MeterID_tb.Text = Regex.Replace(MeterID_tb.Text, "[^A-Za-z0-9]+", "")
'Opco_tb.Text = Regex.Replace(Opco_tb.Text, "[^A-Za-z0-9]+", "")
DateFrom_tb.Text = Regex.Replace(DateFrom_tb.Text, "[^A-Za-z0-9]+", "")
DateTo_tb.Text = Regex.Replace(DateTo_tb.Text, "[^A-Za-z0-9]+", "")
'Don't allow the user to search without a filter. The results returned will be too large
'Opco_tb.Text = "" &
If (MeterID_tb.Text = "") And (Division_db.SelectedValue = "Any") And (DateFrom_tb.Text = "") And (DateTo_tb.Text = "") Then
Dim strScript As String = "<script language=JavaScript>"
strScript += "alert(""" & "You must enter at least one search parameter." & """);"
strScript += "</script>"
If (Not Page.IsStartupScriptRegistered("clientScript")) Then
Page.RegisterStartupScript("clientScript", strScript)
End If
Exit Sub
End If
con = New OleDb.OleDbConnection(*Hidden*)
commandstr = "SELECT METERID as ""Meter ID"", REPID as ""Rep ID"", DIVISION as ""Division"", CITY as ""City"", ADDRESS as ""Address"", RATECODE as ""Ratecode"", METERFORM as ""Meter Form"", METERSTATUS as ""Meter Status"", METERPOINTSTATUS as ""Meter Point Status"", BILLINGCYCLE as ""Billing Cycle"", FILENAME as ""Filename"", FILEDATETIME as ""File Date/Time"" from BAD_METER_LIST"
wherestr = " WHERE"
If MeterID_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " METERID = '" + MeterID_tb.Text + "'"
Else
wherestr = wherestr + " AND METERID = '" + MeterID_tb.Text + "'"
End If
End If
If Division_db.SelectedValue <> "Any" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " DIVISION = " + Division_db.SelectedValue
Else
wherestr = wherestr + " AND DIVISION = " + Division_db.SelectedValue
End If
End If
If DateFrom_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " FILEDATETIME >= to_date('" & DateFrom_tb.Text & "', 'mmddyyyy')"
Else
wherestr = wherestr + " AND FILEDATETIME >= to_date('" & DateFrom_tb.Text & "', 'mmddyyyy')"
End If
End If
If DateTo_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " FILEDATETIME <= to_date('" & DateTo_tb.Text & "', 'mmddyyyy')"
Else
wherestr = wherestr + " AND FILEDATETIME <= to_date('" & DateTo_tb.Text & "', 'mmddyyyy')"
End If
End If
command = New OleDb.OleDbCommand(commandstr + wherestr)
command.Connection = con
con.Open()
oda.SelectCommand = command
oda.Fill(dt)
Me.Grid_Bad_Meters.DataSource = dt
Me.Grid_Bad_Meters.DataBind()
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Grid_Bad_Meters_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles Grid_Bad_Meters.PageIndexChanging
'Grid_Bad_Meters.Visible = True
Grid_Bad_Meters.PageIndex = e.NewPageIndex
Grid_Bad_Meters.DataBind()
End Sub
End Class
You need to rebind the GridView upon changing PageIndex.
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
#Region "Subs"
Private Sub CleanInput()
'Remove any non-aplhanumeric characters from the input string
MeterID_tb.Text = Regex.Replace(MeterID_tb.Text, "[^A-Za-z0-9]+", "")
'Opco_tb.Text = Regex.Replace(Opco_tb.Text, "[^A-Za-z0-9]+", "")
DateFrom_tb.Text = Regex.Replace(DateFrom_tb.Text, "[^A-Za-z0-9]+", "")
DateTo_tb.Text = Regex.Replace(DateTo_tb.Text, "[^A-Za-z0-9]+", "")
End Sub
Private Sub RequireFilter
'Don't allow the user to search without a filter. The results returned will be too large
'Opco_tb.Text = "" &
If ((MeterID_tb.Text = "")
AndAlso (Division_db.SelectedValue = "Any")
AndAlso (DateFrom_tb.Text = "")
AndAlso (DateTo_tb.Text = "")) Then
Dim strScript As String = "<script language=JavaScript>"
strScript += "alert(""" & "You must enter at least one search parameter." & """);"
strScript += "</script>"
If (Not Page.IsStartupScriptRegistered("clientScript")) Then
Page.RegisterStartupScript("clientScript", strScript)
End If
Exit Sub
End If
End Sub
Private Sub FillGridView
Dim con As OleDb.OleDbConnection
Dim command As OleDb.OleDbCommand
Dim commandstr As String
Dim wherestr As String
Dim dt As DataTable = New DataTable
Dim oda As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
con = New OleDb.OleDbConnection(*Hidden*)
commandstr = "SELECT METERID as ""Meter ID"", REPID as ""Rep ID"", DIVISION as ""Division"", CITY as ""City"", ADDRESS as ""Address"", RATECODE as ""Ratecode"", METERFORM as ""Meter Form"", METERSTATUS as ""Meter Status"", METERPOINTSTATUS as ""Meter Point Status"", BILLINGCYCLE as ""Billing Cycle"", FILENAME as ""Filename"", FILEDATETIME as ""File Date/Time"" from BAD_METER_LIST"
wherestr = " WHERE"
If MeterID_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " METERID = '" + MeterID_tb.Text + "'"
Else
wherestr = wherestr + " AND METERID = '" + MeterID_tb.Text + "'"
End If
End If
If Division_db.SelectedValue <> "Any" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " DIVISION = " + Division_db.SelectedValue
Else
wherestr = wherestr + " AND DIVISION = " + Division_db.SelectedValue
End If
End If
If DateFrom_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " FILEDATETIME >= to_date('" & DateFrom_tb.Text & "', 'mmddyyyy')"
Else
wherestr = wherestr + " AND FILEDATETIME >= to_date('" & DateFrom_tb.Text & "', 'mmddyyyy')"
End If
End If
If DateTo_tb.Text <> "" Then
If wherestr = " WHERE" Then
wherestr = wherestr + " FILEDATETIME <= to_date('" & DateTo_tb.Text & "', 'mmddyyyy')"
Else
wherestr = wherestr + " AND FILEDATETIME <= to_date('" & DateTo_tb.Text & "', 'mmddyyyy')"
End If
End If
command = New OleDb.OleDbCommand(commandstr + wherestr)
command.Connection = con
con.Open()
oda.SelectCommand = command
oda.Fill(dt)
Me.Grid_Bad_Meters.DataSource = dt
Me.Grid_Bad_Meters.DataBind()
End Sub
#End Region
Protected Sub Search_Click(sender As Object, e As EventArgs) Handles Search.Click
CleanInput()
RequireFilter()
FillGridView()
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Grid_Bad_Meters_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles Grid_Bad_Meters.PageIndexChanging
'Grid_Bad_Meters.Visible = True
Grid_Bad_Meters.PageIndex = e.NewPageIndex
Grid_Bad_Meters.DataBind()
FillGridView()
End Sub
End Class

Incorrect syntax near ',' (dbnull issue)

It suppose there is chart to be appeared. But, it doesnt as there is problem regarding dbnull issue. This happen when either one of three select statement has no data.
Dim user As String = Session("NoMatrik")
Dim resultId As Object = Session("max")
Dim idQuery = "select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 1 UNION All " +
"select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 2 UNION All " +
"select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 3"
conn.Open()
Dim cmdGetId As New SqlCommand(idQuery, conn)
cmdGetId.Parameters.AddWithValue("#matric", user)
Dim maxIDs As SqlDataReader = cmdGetId.ExecuteReader
Dim IDs As String = ""
While maxIDs.Read
IDs += maxIDs("id").ToString() + ", "
End While
maxIDs.Close()
IDs = IDs.Substring(0, IDs.Length - 2)
Dim cmdString = "Select tblResult.result_quiz_id as Quiz,count(TblAnswer.AnswerType) as answerCount , TblAnswer.AnswerType " +
"from TblResultDetail inner join TblAnswer on TblResultDetail.ResultDetail_Answer_Id = TblAnswer.AnswerId " +
"inner join tblResult on tblResult.resultid = TblResultDetail.ResultDetail_Result_Id " +
"where TblResultDetail.ResultDetail_Result_Id in (" + IDs + ") " +
"group by TblAnswer.AnswerType, tblResult.result_quiz_id order by TblAnswer.AnswerType"
Dim cmd As New SqlCommand(cmdString, conn)
If IsDBNull(resultId) Then
Label1.Visible = True
chrtResult.Visible = False
Else
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
While dr1.Read()
Dim tempArr(0) As Double
Dim count As Double = dr1("answerCount")
tempArr(0) = count
Dim Type As String = dr1("AnswerType").ToString()
Dim level As Integer = dr1("Quiz")
chrtResult.Series(Type).Points(level - 1).YValues = tempArr
End While
End If
conn.Close()
End If
End Sub
an error, Incorrect syntax near '(' appear at line dr1 = cmd.ExecuteReader. So , how I want to fix this error?
Update your first query to exclude any Null values using a HAVING clause like so:
Dim idQuery = "select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 1 " +
"having max(resultid) is not null " +
"UNION All " +
"select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 2 " +
"having max(resultid) is not null " +
"UNION All " +
"select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 3 " +
"having max(resultid) is not null"
The having max(resultid) is not null will exclude any nulls in your UNION ALL.
If there are no IDs returned, you simply need to do a check on this before you execute your next block of code and do as #DmitriE suggests with the adding of quotes. Reorganise it to look like:
While maxIDs.Read
IDs += "'" + maxIDs("id").ToString() + "', "
End While
If IDs = "" Then
Label1.Visible = True
chrtResult.Visible = False
Else
IDs = IDs.Substring(0, IDs.Length - 2)
Dim cmdString = "Select ....."
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
While dr1.Read()
' YOUR WHILE LOOP CODE HERE'
End While
End If
This should be
While maxIDs.Read
IDs += "'" + maxIDs("id").ToString() + "', "
End While
and then you need to remove last single quote.
in clause should follow this format: where x.id in ('id1', 'id2', 'idN')

TreeView expanding wrong node

I have a TreeView in a VB.NET/ASP.NET Application.
The TreeView is being Populated programmatically as the page loads. However, when i try and expand a node it is expanding the wrong node.
Example:I have a node with 5 children. Nodes one and two have children and when i try and expand node two it expands node one and when i try and expand node one it also expands node one.
I have tried re-organizing the structure of the TreeView and Also tried adding the nodes in one by one and still no luck.
Edit:
Below is the Relevant code from my TreeView :
For Each V2MaterialRow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Material Details'", connection)
Dim FormName As String = command.ExecuteScalar()
connection.Close()
V2MaterialNode = New TreeNode
V2MaterialNode.ToolTip = "V2 Material Details"
V2MaterialNode.Text = FormName & " " & V2MaterialRow("Version")
V2MaterialNode.Value = V2MaterialRow("Qno")
V2MaterialNode.ShowCheckBox = True
V2MaterialNode.NavigateUrl = "V2MaterialDetails.aspx?text=" + V2MaterialRow("Qno")
V2MaterialNode.Target = "_blank"
node.ChildNodes.Add(V2MaterialNode)
connection.Open()
command = New SqlCommand("Select * from Specallinone where qno='" + V2MaterialRow("Qno") + "'", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
For Each PurchaseOrderRow In DS.Tables("PurchaseOrder").Rows
PurchaseOrderNode = New TreeNode
PurchaseOrderNode.ToolTip = "Purchase Order"
PurchaseOrderNode.Text = "Purchase Order - " + PurchaseOrderRow("supplier") + " " + PurchaseOrderRow("Ordernumber")
PurchaseOrderNode.Value = PurchaseOrderRow("Qno")
PurchaseOrderNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + PurchaseOrderRow("Qno") + "&Jobno=" + PurchaseOrderRow("JobNumber") + "&Orderno=" + PurchaseOrderRow("Ordernumber") + "&text=" + Replace(PurchaseOrderRow("supplier"), "&", "$") + ""
PurchaseOrderNode.Target = "_blank"
V2MaterialNode.ChildNodes.Add(PurchaseOrderNode)
Next
Else
datareader.Close()
End If
connection.Close()
For Each LabelRow As DataRow In DS.Tables("AllinOne").Rows
Dim Labelnode = New TreeNode
Labelnode.ToolTip = "PO Labels"
Labelnode.Text = "PO Labels"
Labelnode.Value = LabelRow("Qno")
'Labelnode.ShowCheckBox = True
Labelnode.NavigateUrl = "GeneratePOLabels.aspx?text=" + LabelRow("Qno")
Labelnode.Target = "_blank"
Try
connection.Open()
command = New SqlCommand("Select * from purchaseorder where qno='" + LabelRow("Qno") + "' and Jobnumber<>''", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
Exit For
Else
datareader.Close()
V2MaterialNode.ChildNodes.Add(Labelnode)
End If
Catch ex As Exception
Messagebox.Show("Error in Dispalying the Labels...")
Finally
connection.Close()
End Try
Next
Next
For Each MPORow In DS.Tables("ManualPO").Rows
Dim Supplier As String
connection.Open()
command = New SqlCommand("Select Distinct Supplier from ManualPurchaseOrder where ManualDetailsId='" + MPORow("ManualDetailsId").ToString + "' ", connection)
datareader = command.ExecuteReader()
While datareader.Read()
Supplier = Supplier + datareader.Item("Supplier") + ","
End While
datareader.Close()
connection.Close()
MPONode = New TreeNode
MPONode.Value = MPORow("ManualDetailsId")
MPONode.Text = "Manual PO " & MPORow("ManualDetailsId") & " Supplier:" & Supplier.ToString
Supplier = ""
node.ChildNodes.Add(MPONode)
Dim ManualPODetailsDa As New SqlDataAdapter("Select distinct supplier,Jobnumber,ordernumber,Qno from PurchaseOrder where Ordernumber in (Select Distinct OrderNumber From ManualPurchaseOrder where ManualDetailsId = '" + MPORow("ManualDetailsId") + "') ", connection)
Dim ManualPODetailsDs As New DataSet
ManualPODetailsDa.Fill(ManualPODetailsDs)
For Each ManualPODetailsDR As DataRow In ManualPODetailsDs.Tables(0).Rows
MPODNode = New TreeNode
MPODNode.Value = ManualPODetailsDR("OrderNumber")
MPODNode.Text = "Purchase Order - " + ManualPODetailsDR("supplier") + " " + ManualPODetailsDR("Ordernumber")
MPODNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + ManualPODetailsDR("Qno") + "&Jobno=" + ManualPODetailsDR("JobNumber") + "&Orderno=" + ManualPODetailsDR("Ordernumber") + "&text=" + Replace(ManualPODetailsDR("supplier"), "&", "$") + ""
MPODNode.Target = "_blank"
MPONode.ChildNodes.Add(MPODNode)
Next
Next
For Each Takeoffrow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Take-Off-Sheets'", connection)
Dim FormName As String = command.ExecuteScalar()
TakeOffNode = New TreeNode
TakeOffNode.ToolTip = "Take Off Sheets"
TakeOffNode.Text = FormName & " " & Takeoffrow("Version")
TakeOffNode.Value = Takeoffrow("Qno")
TakeOffNode.ShowCheckBox = True
TakeOffNode.NavigateUrl = "TakeOffSheet.aspx?text=" + Takeoffrow("Qno")
TakeOffNode.Target = "_blank"
node.ChildNodes.Add(TakeOffNode)
command = New SqlCommand("Select count(*) from ManualTakeOffSheet where srecid in (Select Distinct Srecid from Specdetails where Quoteno='" + Takeoffrow("Qno") + "')", connection)
Dim MTS As Integer = 0
MTS = command.ExecuteScalar()
connection.Close()
If MTS > 0 Then
Dim ManualTakeoffnode As New TreeNode
ManualTakeoffnode.ToolTip = "Manual Take Off Sheets"
ManualTakeoffnode.Text = "Manual Take Off Sheets" & " " & Takeoffrow("Version")
ManualTakeoffnode.Value = Takeoffrow("Qno")
ManualTakeoffnode.NavigateUrl = "ManualTakeOffSheet.aspx?text=" + Takeoffrow("Qno")
ManualTakeoffnode.Target = "_blank"
TakeOffNode.ChildNodes.Add(ManualTakeoffnode)
End If
Next
Sometimes if you have a node which shares the same value as another node - unexpected behavior can occur (one node opening when the other is clicked)
Node values must be unique
Debug your code and ensure that all your nodes have a unique value.
The value will be stored in node.Value
In your case, the node.Value is populated from a table.
Ensure that TakeOffNode.Value = Takeoffrow("Qno") does not equal MPODNode.Value = ManualPODetailsDR("OrderNumber")

SQL Server 2012 - ASP.NET - VB.NET - Insert Data into database

I am trying to insert data to a db table using SQL statement with VB.NET.
This is my code:
Registration.aspx:
Imports dbConnect
Imports System.Data.SqlClient
Partial Class Registration
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
register()
End Sub
Public Sub register()
Dim Username As String = txtUsername.ToString
Dim Surname As String = txtSurname.ToString
Dim Password As String = txtPassword.ToString
Dim Name As String = txtName.ToString
Dim Address1 As String = txtAddress1.ToString
Dim Address2 As String = txtAddress2.ToString
Dim City As String = txtCity.ToString
Dim Email As String = txtEmail.ToString
Dim Country As String = drpCountry.ToString
Dim DOB As Date = calDOB.SelectedDate
Dim Occupation As String = txtOccupation.ToString
Dim WorkLocation As String = txtWorkLocation.ToString
Dim Age As Integer = "20"
Dim ProjectManager As String = "test"
Dim TeamLeader As String = "test"
Dim TeamLeaderID As Integer = 1
Dim ProjectManagerID As Integer = 1
Dim RegistrationDate As Date = Today
Dim ContractType As String = "test"
Dim ContractDuration As Integer = 6
Dim Department As String = "test"
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
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('" + Username + "','" + Password + "','" + Name + "','" + Surname + "','" + Address1 + "','" + Address2 + "','" + City + "','" + Country + "','" + DOB + "','" + Age + "','" + Occupation + "','" + Department + "','" + WorkLocation + "','" + ProjectManager + "','" + TeamLeader + "','" + TeamLeaderID + "','" + ProjectManager + "','" + RegistrationDate + "','" + ContractType + "','" + ContractDuration + "')"
conn.Open()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.ExecuteNonQuery()
conn.Close()
End Sub
End Class
This is my database 'users' table:
I am getting this error message:
Error 1 Operator '+' is not defined for types 'Double' and 'Date'. C:\Users\Brian\Documents\Visual Studio 2012\WebSites\WebSite1\Registration.aspx.vb 51 19 WebSite1(1)
Can anyone tell me whats going on ?
As Lloyd pointed out, parameterize your queries. E.g. (shortened for readability)
sqlComm = "INSERT INTO users(Username, Password, Name) VALUES(#Username, #Password, #Name)"
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("#Username", Username)
registerSQL.Parameters.AddWithValue("#Password", Password)
registerSQL.Parameters.AddWithValue("#Name", Name)
But to answer your question, use & instead of + to concatenate a String.
Just to give you a starting point
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()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("#p1", Username)
.....
registerSQL.ExecuteNonQuery()
And when the value to pass to the AddWithValue method is not a string, try to convert to the correct datatype expected by the database field.
registerSQL.Parameters.AddWithValue("#p9", Convert.ToDateTime(DOB))
In this way you don't have to worry about parsing strings with double quotes or automatic conversion of strings to date, moreover, you don't have problems with Sql Injection attacks

Resources