SQL statement in for loop only updating once - asp-classic

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

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

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

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

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.

How to Display images 100x75, and on click, display them in original size. ASP classic

The code below first displays folders as hyperlinks, you can click into these folders and if they contain JPG's it will display them.
Is it possible to make these images display with attributes width="100" height="75" but still allow me to click them and have them display original size?
<%
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
qfolder = request.querystring("f")
if qfolder = "" then
folderspec = server.mappath(".")
Set filesys = CreateObject("Scripting.FileSystemObject")
Set demofolder = filesys.GetFolder(folderspec)
Set folcoll = demofolder.SubFolders
For Each subfol in folcoll
folsize = left((subfol.size/1000000), 3)
folist = folist & "<a href='?f=" & subfol.name & "'><strong title='view'></strong> " & subfol.Name & "" & vbcrlf
folist = folist & "<BR>"
Next
set filesys = nothing
Response.Write folist
else
filepath = server.mappath(".") & "\" & qfolder
captionfile = filepath & "\captions.txt"
Set filesys = CreateObject("Scripting.FileSystemObject")
Dim SomeArray()
'caption part
If filesys.FileExists(captionfile) then
set file = filesys.GetFile(captionfile)
Set TextStream = file.OpenAsTextStream(ForReading,TristateUseDefault)
captioncount = 0
Do While Not TextStream.AtEndOfStream
Line = TextStream.readline
ReDim Preserve SomeArray(captioncount)
SomeArray(captioncount) = line
'response.write captioncount & " " & somearray(captioncount) & "<br>"
captioncount = captioncount + 1
'Response.write Line
Loop
textStream.close
end if
'folder part
Set demofolder = filesys.GetFolder(filepath)
Set filecoll = demofolder.Files
filecount = 0
For Each file in filecoll
Ext = UCase(Right(File.Path, 3))
If Ext = "JPG" OR Ext = "GIF" Then
on error resume next
data = SomeArray(filecount)
on error goto 0
hrefpath = qfolder & "/" & file.name
imagepath = "<strong>" & data & "</strong><br><a href='" & hrefpath & "' title='free image gallery' border=0><img src='" & hrefpath & "' border='" & border_size & "' title=""" & data & """ style='border-color: " & border_color & ";'></a><br>"
filist = filist & imagepath & vbcrlf
filist = filist & "<BR>"
filecount = filecount + 1
data = ""
end if
Next
set filesys = Nothing
filist = filist & "<br><small><a href='http://www.allscoop.com/' target='_blank'>allscoop free image gallery</a></small>"
%>
<h3>«
<%=qfolder%></h3>
<p><%=filist%></p>
<% end if %>
Thanks
You need to update a single line where tag is created:
imagepath = "<strong>" & data & "</strong><br><a href='" & hrefpath & _
"' title='free image gallery' border=0><img width=100 height=75 src='" &_
hrefpath & "' border='" & border_size & "' title=""" & data &_
""" style='border-color: " & border_color & ";'></a><br>"
Just in case here is complete script:
<%
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
qfolder = request.querystring("f")
if qfolder = "" then
folderspec = server.mappath(".")
Set filesys = CreateObject("Scripting.FileSystemObject")
Set demofolder = filesys.GetFolder(folderspec)
Set folcoll = demofolder.SubFolders
For Each subfol in folcoll
folsize = left((subfol.size/1000000), 3)
folist = folist & "<a href='?f=" & subfol.name & "'><strong title='view'></strong> " & subfol.Name & "" & vbcrlf
folist = folist & "<BR>"
Next
set filesys = nothing
Response.Write folist
else
filepath = server.mappath(".") & "\" & qfolder
captionfile = filepath & "\captions.txt"
Set filesys = CreateObject("Scripting.FileSystemObject")
Dim SomeArray()
'caption part
If filesys.FileExists(captionfile) then
set file = filesys.GetFile(captionfile)
Set TextStream = file.OpenAsTextStream(ForReading,TristateUseDefault)
captioncount = 0
Do While Not TextStream.AtEndOfStream
Line = TextStream.readline
ReDim Preserve SomeArray(captioncount)
SomeArray(captioncount) = line
'response.write captioncount & " " & somearray(captioncount) & "<br>"
captioncount = captioncount + 1
'Response.write Line
Loop
textStream.close
end if
'folder part
Set demofolder = filesys.GetFolder(filepath)
Set filecoll = demofolder.Files
filecount = 0
For Each file in filecoll
Ext = UCase(Right(File.Path, 3))
If Ext = "JPG" OR Ext = "GIF" Then
on error resume next
data = SomeArray(filecount)
on error goto 0
hrefpath = qfolder & "/" & file.name
imagepath = "<strong>" & data & "</strong><br><a href='" & hrefpath & "' title='free image gallery' border=0><img width=100 height=75 src='" & hrefpath & "' border='" & border_size & "' title=""" & data & """ style='border-color: " & border_color & ";'></a><br>"
filist = filist & imagepath & vbcrlf
filist = filist & "<BR>"
filecount = filecount + 1
data = ""
end if
Next
set filesys = Nothing
filist = filist & "<br><small><a href='http://www.allscoop.com/' target='_blank'>allscoop free image gallery</a></small>"
%>
<h3>«
<%=qfolder%></h3>
<p><%=filist%></p>
<% end if %>

datagrid view is not showing data

I try this code for showing some info from sql database. but I can not see the datas in gridview..How can I solve?? Also, I have no error.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection("Server=CAN-PC; Database=SMS; UID=SA; PWD=delidana1963");
string sql = "";
sql = #"select Orginator,RecordDate, (select COUNT(TurkcellID) from SmsStore ";
// txttarih.Text = Calendar1.SelectedDate.ToString();
var tarih1 = String.Format("{0:yyyy-MM-dd hh:mm}", Calendar1.SelectedDate.Date);
var tarih2 = String.Format("{0:yyyy-MM-dd hh:mm}", Calendar2.SelectedDate.Date);
if (Calendar1.SelectedDate != null && Calendar2.SelectedDate != null)
sql += "where RecordDate between '" +tarih1 + "' and '" + tarih2 + "'";
else if (Calendar1.SelectedDate != null && Calendar2.SelectedDate == null)
sql += "where RecordDate between '" + tarih1 + "' and '" + DateTime.Now + "'";
sql += ") as toplammsj,";
sql += "(select COUNT(TurkcellID) from SmsStore where TurkcellID=1 ";
if (Calendar1.SelectedDate != null && Calendar2.SelectedDate != null)
sql += "and RecordDate between '" + tarih1 + "' and '" + tarih2+ "'";
else if (Calendar1.SelectedDate != null && Calendar2.SelectedDate == null)
sql += "and RecordDate between '" + tarih1 + "' and '" + DateTime.Now + "'";
sql += ") as giden,";
sql += " (select COUNT(TurkcellID) from SmsStore where TurkcellID=0 ";
if (Calendar1.SelectedDate != null && Calendar2.SelectedDate != null)
sql += "and RecordDate between '" + tarih1 + "' and '" + tarih2 + "'";
else if (Calendar1.SelectedDate != null && Calendar2.SelectedDate == null)
sql += "and RecordDate between '" + tarih1 + "' and '" + DateTime.Now + "'";
sql += ") as gitmeyen from SmsStore ";
if (Calendar1.SelectedDate != null && Calendar2.SelectedDate != null)
sql += "where RecordDate between '" + tarih1+ "' and '" + tarih2 + "'";
else if (Calendar1.SelectedDate != null && Calendar2.SelectedDate == null)
sql += "where RecordDate between '" + tarih1 + "' and '" + DateTime.Now + "'";
SqlDataAdapter adp = new SqlDataAdapter(sql, cnn);
DataTable dt = new DataTable();
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.DataMember = "dt";
}
please help me about this problem.
thanks for all.
Is this a WPF GridView or a Windows Forms DataGridView? The WPF GridView does not have a DataSource property or DataBind() method. And for a DataGridView, you do not need to use DataBind() or set the DataMember property if the DataSource is a DataTable, as you have done.
Also, for debugging purposes put a breakpoint after the line adp.Fill(dt). Put your cursor over dt and examine the properties to determine if Rows.Count is greater than 0. If your SQL is messed up, you might not be getting any data from the database in the first place.

Resources