My website only shows user profiles with the first 2 ID numbers. How can I display all user profiles correctly? - asp.net

I´m doing a website in VB.NET that allows users to create and view profiles. For the first two users, the profile shows perfectly, but for any user with an ID number equal or higher than three it doesn't work. What could be the reason for that and how can I fix it?
This is the code that loads the profile in a webform:
Public Sub cargarPerfil(cnn As SqlConnection, cmd As SqlCommand)
Dim perfil, nombre, nick, pais, ciudad, codigo, telefono, nacimiento, nivel, tipo1, tipo2 As String
Dim social, artistico, comercial, rango, titulo1, titulo2, titulo3, foto, credito As String
Dim da As New SqlDataAdapter
Dim dt As DataTable
perfil = "SELECT USUARIONOMBREREAL, USUARIONICK, PAISNOMBRE AS PAIS, CIUDADNOMBRE AS CIUDAD, USUARIOCODIGO, USUARIOTELEFONO, USUARIONACIMIENTO, " & _
"TIPONOMBRE AS TIPO1, NIVELNOMBRE AS NIVEL, USUARIOSOCIAL, USUARIOARTISTICO, USUARIOCOMERCIAL, USUARIOFOTO, USUARIOCREDITO, " & _
"RANGONOMBRE AS RANGO, TITULONOMBRE AS TITULO1 FROM USUARIO " & _
"INNER JOIN PAIS ON USUARIO.USUARIOPAIS = PAIS.PAISID " & _
"INNER JOIN CIUDAD ON USUARIO.USUARIOCIUDAD = CIUDADID " & _
"INNER JOIN TIPO ON USUARIO.USUARIOTIPO1 = TIPO.TIPOID " & _
"INNER JOIN NIVEL ON USUARIO.USUARIONIVEL = NIVEL.NIVELID " & _
"INNER JOIN RANGO ON USUARIO.USUARIORANGO = RANGO.RANGOID " & _
"INNER JOIN TITULO ON USUARIO.USUARIOTITULO1 = TITULO.TITULOID " & _
"WHERE USUARIOID = '" & Session(Principal.User.UserID) & "' AND USUARIONICK = '" & Session(Principal.User.UserName) & "'"
With cmd
.CommandType = CommandType.Text
.CommandText = perfil
.Connection = cnn
End With
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
nombre = dt.Rows.Item(0).Item("USUARIONOMBREREAL")
nick = dt.Rows.Item(0).Item("USUARIONICK")
pais = dt.Rows.Item(0).Item("PAIS")
ciudad = dt.Rows.Item(0).Item("CIUDAD")
codigo = dt.Rows.Item(0).Item("USUARIOCODIGO")
telefono = dt.Rows.Item(0).Item("USUARIOTELEFONO")
nacimiento = dt.Rows.Item(0).Item("USUARIONACIMIENTO")
tipo1 = dt.Rows.Item(0).Item("TIPO1")
nivel = dt.Rows.Item(0).Item("NIVEL")
social = dt.Rows.Item(0).Item("USUARIOSOCIAL")
artistico = dt.Rows.Item(0).Item("USUARIOARTISTICO")
comercial = dt.Rows.Item(0).Item("USUARIOCOMERCIAL")
rango = dt.Rows.Item(0).Item("RANGO")
titulo1 = dt.Rows.Item(0).Item("TITULO1")
foto = "~/0/" + nombre + ".jpg"
credito = dt.Rows.Item(0).Item("USUARIOCREDITO")
dt = Nothing
perfil = "SELECT TIPONOMBRE AS TIPO2, TITULONOMBRE AS TITULO2 FROM USUARIO " & _
"INNER JOIN TIPO ON USUARIO.USUARIOTIPO2 = TIPO.TIPOID " & _
"INNER JOIN TITULO ON USUARIO.USUARIOTITULO2 = TITULO.TITULOID " & _
"WHERE USUARIOID = '" & Session(Principal.User.UserID) & "' AND USUARIONICK = '" & Session(Principal.User.UserName) & "'"
With cmd
.CommandType = CommandType.Text
.CommandText = perfil
.Connection = cnn
End With
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
tipo2 = dt.Rows.Item(0).Item("TIPO2")
titulo2 = dt.Rows.Item(0).Item("TITULO2")
dt = Nothing
perfil = "SELECT TITULONOMBRE AS TITULO3 FROM USUARIO INNER JOIN TITULO ON USUARIO.USUARIOTITULO3 = TITULO.TITULOID " & _
"WHERE USUARIOID = '" & Session(Principal.User.UserID) & "' AND USUARIONICK = '" & Session(Principal.User.UserName) & "'"
With cmd
.CommandType = CommandType.Text
.CommandText = perfil
.Connection = cnn
End With
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
titulo3 = dt.Rows.Item(0).Item("TITULO3")
dt = Nothing
lblNombre.Text = nombre
lblNick.Text = nick
lblPais.Text = pais
lblCiudad.Text = ciudad
lblCodigo.Text = codigo
lblTelefono.Text = telefono
lblNacimiento.Text = nacimiento
lblTipo1.Text = tipo1
lblTipo2.Text = tipo2
lblNivel.Text = nivel
lblSocial.Text = social
lblArtistico.Text = artistico
lblComercial.Text = comercial
lblRango.Text = rango
lblTitulo1.Text = titulo1
lblTitulo2.Text = titulo2
lblTitulo3.Text = titulo3
imgPerfil.ImageUrl = foto
lblCredito.Text = credito
End Sub
This is the code that creates profiles in a different webform:
Private Sub registro(cnn As SqlConnection, cmd As SqlCommand)
Dim nuevo, nombre, nick, pass, mail, pais, ciudad, codigo, telefono, nacimiento, nivel, tipo1, tipo2 As String
Dim social, artistico, comercial, rango, titulo1, titulo2, titulo3, foto, contrato As String
Dim savePathF As String = "F:\ComparteME\ComparteME\0\"
Dim savePathC As String = "F:\ComparteME\ComparteME\Reconocimientos\"
Dim fileNameF As String = txtNombreReal.Text + ".jpg"
Dim fileNameC As String = "Reconocimiento - " + txtNombreReal.Text + ".jpg"
Dim pathToCheckF As String = savePathF + fileNameF
Dim pathToCheckC As String = savePathC + fileNameC
Dim tempfileNameF As String = ""
Dim tempfileNameC As String = ""
nuevo = ""
nombre = txtNombreReal.Text
nick = txtNick.Text
pass = txtPassword.Text
mail = txtMail.Text
pais = ddlPais.SelectedValue
ciudad = ddlCiudad.SelectedValue
codigo = txtCodigo.Text
telefono = txtTelefono.Text
nacimiento = txtNacimiento.Text
nivel = ddlNivel.SelectedValue
tipo1 = ddlTipo1.SelectedValue
tipo2 = ddlTipo2.SelectedValue
foto = ""
contrato = ""
social = 0
artistico = 0
comercial = 0
rango = 1
titulo1 = 0
titulo2 = 0
titulo3 = 0
If (uplFoto.HasFile) Then
If (System.IO.File.Exists(pathToCheckF)) Then
Dim counter As Integer = 0
While (System.IO.File.Exists(pathToCheckF))
tempfileNameF = counter.ToString() + fileNameF
pathToCheckF = savePathF + tempfileNameF
counter = counter + 1
End While
If counter > 0 Then
fileNameF = tempfileNameF
End If
End If
savePathF += fileNameF
uplFoto.SaveAs(savePathF)
foto = savePathF
End If
If (uplReconocimiento.HasFile) Then
If (System.IO.File.Exists(pathToCheckC)) Then
Dim counter As Integer = 0
While (System.IO.File.Exists(pathToCheckC))
tempfileNameC = counter.ToString() + fileNameC
pathToCheckC = savePathC + tempfileNameC
counter = counter + 1
End While
If counter > 0 Then
fileNameC = tempfileNameC
End If
End If
savePathC += fileNameC
uplReconocimiento.SaveAs(savePathC)
contrato = savePathC
End If
nuevo = "INSERT INTO USUARIO (USUARIOID, USUARIONOMBREREAL, USUARIONICK, USUARIOPASSWORD, USUARIOENCRIPTADO, USUARIOCORREO, USUARIOPAIS, USUARIOCIUDAD, USUARIOCODIGO, USUARIOTELEFONO, " & _
"USUARIONACIMIENTO, USUARIOTIPO1, USUARIOTIPO2, USUARIONIVEL, USUARIOSOCIAL, USUARIOARTISTICO, USUARIOCOMERCIAL, USUARIORANGO, USUARIOTITULO1, USUARIOTITULO2, " & _
"USUARIOTITULO3, USUARIOFOTO, USUARIOCONTRATO) " & _
"SELECT (ISNULL(MAX(USUARIOID), 0)+1), '" & nombre & "', '" & nick & "', '" & pass & "', PWDENCRYPT('" & pass & "'), '" & mail & "', " & pais & ", " & ciudad & ", " & codigo & ", " & _
"" & telefono & ", '" & nacimiento & "', " & tipo1 & ", " & tipo2 & ", " & nivel & ", " & social & ", " & artistico & ", " & comercial & ", " & rango & ", " & _
"" & titulo1 & ", " & titulo2 & ", " & titulo3 & ", '" & foto & "', '" & contrato & "' FROM USUARIO "
cnn.Open()
cmd.CommandText = nuevo
cmd.Connection = cnn
cmd.ExecuteNonQuery()
cnn.Close()
lblSuccess.Text = "¡Bienvenido a ComparteME! En un momento se comprobar&aacuten tus datos y tu cuenta será activada. Intenta iniciar sesión."
tblRegistro.Visible = False
tblSuccess.Visible = True
End Sub
Even when I do the query directly in SQLServer, it only loads the data when ID < 3, not any higher. SQL is like this:
SELECT
USUARIONOMBREREAL,
USUARIONICK,
PAISNOMBRE AS PAIS,
CIUDADNOMBRE AS CIUDAD,
USUARIOCODIGO,
USUARIOTELEFONO,
USUARIONACIMIENTO,
TIPONOMBRE AS TIPO1,
NIVELNOMBRE AS NIVEL,
USUARIOSOCIAL,
USUARIOARTISTICO,
USUARIOCOMERCIAL,
USUARIOFOTO,
USUARIOCREDITO,
RANGONOMBRE AS RANGO,
TITULONOMBRE AS TITULO1
FROM
USUARIO
INNER JOIN PAIS ON USUARIO.USUARIOPAIS = PAIS.PAISID
INNER JOIN CIUDAD ON USUARIO.USUARIOCIUDAD = CIUDADID
INNER JOIN TIPO ON USUARIO.USUARIOTIPO1 = TIPO.TIPOID
INNER JOIN NIVEL ON USUARIO.USUARIONIVEL = NIVEL.NIVELID
INNER JOIN RANGO ON USUARIO.USUARIORANGO = RANGO.RANGOID
INNER JOIN TITULO ON USUARIO.USUARIOTITULO1 = TITULO.TITULOID
WHERE
USUARIOID = '1' AND USUARIONICK = 'SpuntikPPV'

Since a lot of information is missing, I'm going to guess.
I think one of the tables you are joining to has just two records that join to your first two users. The other users do not have matching records in the other tables so they are omitted.

Related

how to select from sql database where data not in table1 need to select from table2 +asp.net vb

I have two table FixedAssetMaster_ora and FixedAssetMaster_old. What i want to do is check first if the data exist in FixedAsset_old or not. If exist, select dta from that table, if not exist, need to select data from FixedAssetMaster_ora.Currently my code always select data from FixedAssetMaster_ora.
here is my code:
Dim reccount As String = 0
Conn = New SqlConnection
Conn.ConnectionString = ConnStr
Conn.Open()
cmd = New SqlCommand
cmd.CommandText = "Select COUNT(*) FROM FixedAssetMaster_old WHERE ASSET_NUMBER=" & AssetTxt.Text & " And LOC_DEPT=" & DeptTxt.Text & " AND UNIT_NO='" & UnitNoTxt.Text & "' AND (DATEPART(MM, UPDATE_DATE) = " & nowMonth & ") AND (DATEPART(yyyy, UPDATE_DATE) =" & nowYear & ") ;"
cmd.Connection = Conn
rdmysql = cmd.ExecuteReader
If rdmysql.Read = True Then
'reccount = rdmysql.GetString(0)
reccount = Val(rdmysql.GetInt32(0))
End If
cmd.Dispose()
rdmysql.Close()
If reccount = 0 Then
strsql = "Select * FROM FixedAssetMaster_old WHERE ASSET_NUMBER=" & AssetTxt.Text & " AND LOC_DEPT=" & DeptTxt.Text & " AND UNIT_NO='" & UnitNoTxt.Text & "' And (DATEPART(MM, UPDATE_DATE) = " & nowMonth & ") And (DATEPART(yyyy, UPDATE_DATE) =" & nowYear & ") ;"
cmd.Connection = Conn
cmd.CommandText = strsql
rdmysql = cmd.ExecuteReader
If rdmysql.Read = True Then
If rdmysql.IsDBNull(rdmysql.GetOrdinal("ASSET_KEY_SEGMENT3")) = False Then LocationTxt.Text = rdmysql.GetString(rdmysql.GetOrdinal("ASSET_KEY_SEGMENT3"))
'If rdmysql.IsDBNull(rdmysql.GetOrdinal("REMARKS")) = False Then RemarksTxt.Text = rdmysql.GetString(rdmysql.GetOrdinal("REMARKS"))
'If rdmysql.IsDBNull(rdmysql.GetOrdinal("REMARKS")) = False Then DDLRemarks.Text = rdmysql.GetString(rdmysql.GetOrdinal("REMARKS"))
End If
cmd.Dispose()
rdmysql.Close()
ElseIf reccount = 1 Then
strsql = "Select * FROM FixedAssetMaster_Ora WHERE ASSET_NUMBER=" & AssetTxt.Text & " AND LOC_DEPT='" & DeptTxt.Text & " ';"
cmd.Connection = Conn
cmd.CommandText = strsql
rdmysql = cmd.ExecuteReader
If rdmysql.Read = True Then
If rdmysql.IsDBNull(rdmysql.GetOrdinal("ASSET_KEY_SEGMENT3")) = False Then LocationTxt.Text = rdmysql.GetString(rdmysql.GetOrdinal("ASSET_KEY_SEGMENT3"))
'If rdmysql.IsDBNull(rdmysql.GetOrdinal("REMARKS")) = False Then RemarksTxt.Text = rdmysql.GetString(rdmysql.GetOrdinal("REMARKS"))
'If rdmysql.IsDBNull(rdmysql.GetOrdinal("REMARKS")) = False Then DDLRemarks.Text = rdmysql.GetString(rdmysql.GetOrdinal("REMARKS"))
End If
cmd.Dispose()
rdmysql.Close()
End If
Can someone help me regarding this matter. Thank you in advance
Based on comments, I have re-worked this answer and created a quick/small Unit Test project to verify its functionality is what I understand of the problem.
<TestMethod()>
Public Sub TestGetRecordFromDatabase()
Dim targetRecord As String = "Jay2"
Dim recordIn_OldTable As Boolean = DoesRecordExistIn_Old(targetRecord)
Dim targetTable = "JayV_old"
If Not recordIn_OldTable Then
targetTable = "JayV_ora"
End If
Dim connectionString As String = "Server=MyDBServer; Database=TestingDB; Trusted_Connection=True;"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim sql As String = "SELECT * FROM " & targetTable & " where name = #name"
Using command As SqlCommand = conn.CreateCommand()
command.Parameters.Add(New SqlParameter With {.ParameterName = "name", .DbType = SqlDbType.VarChar, .Value = targetRecord})
command.Connection = conn
command.CommandType = CommandType.Text
command.CommandText = sql
Dim dataReader As SqlDataReader = command.ExecuteReader
While dataReader.Read
Dim name As String = dataReader.GetString(dataReader.GetOrdinal("name"))
Dim address As String = dataReader.GetString(dataReader.GetOrdinal("address"))
End While
End Using
conn.Close()
End Using
End Sub
Public Function DoesRecordExistIn_Old(targetRecord As String) As Boolean
Dim connectionString As String = "Server=MyDBServer; Database=TestingDB; Trusted_Connection=True;"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim sql As String = "SELECT count(*) FROM JayV_old where name = #name"
Using command As SqlCommand = conn.CreateCommand()
command.Parameters.Add(New SqlParameter With {.ParameterName = "name", .DbType = SqlDbType.VarChar, .Value = targetRecord})
command.Connection = conn
command.CommandType = CommandType.Text
command.CommandText = sql
Dim objResult As Object = command.ExecuteScalar()
Dim rowCount As Int32 = Int32.Parse(objResult)
If rowCount = 0 Then
Return False
Else
Return True
End If
End Using
conn.Close()
End Using
End Function
I re-created parts of your problem to encompass the logic of the code you have shared. I believe this works as you would like:
Check for existence of record in _old table
If it exists, load record from _old table
If it does not exist, load record from _ora table
I also re-factored the code to make it easier to maintain as the only difference between the two record retrievals is the Table Name, _old or _ora
I am not very familiar with VB but in C# you can do this as:
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
cmd.CommandText = "Select count(*) from FixedAssetMaster_old WHERE ASSET_NUMBER=" & AssetTxt.Text & " And LOC_DEPT=" & DeptTxt.Text & " AND UNIT_NO='" & UnitNoTxt.Text & "' AND (DATEPART(MM, UPDATE_DATE) = " & nowMonth & ") AND (DATEPART(yyyy, UPDATE_DATE) =" & nowYear & ") ;";
cmd.Connection = con;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
//Select from FixedAssetMaster_old table
}
else
{
//Select FROM FixedAssetMaster_Ora table
}

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')

SQL statement in for loop only updating once

if request.form("submitChange") = "site" then
for i = 0 to UBound(arrmode)
SQLstr = "UPDATE SCSer SET Ser_Site_Num = '" & request.form("site_to") & "' WHERE Ser_Num = '" & arrmode(i) & "'"
conn.execute(SQLstr)
Response.Write("SUCCESSFULLY UPDATED! " + arrmode(i))
next
end if

Resources