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')
Related
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
}
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
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")
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án 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.
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