VB ASP Array prevent multi reading - asp.net

This is my 'code':
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim arrName As New ArrayList()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rdr As SqlDataReader
con.ConnectionString = "Data Source=.\sqlexpress;Initial Catalog=GradingSystemSample;Integrated Security=True;Pooling=False"
cmd.Connection = con
con.Open()
cmd.CommandText = "select numb FROM Table2 "
rdr = cmd.ExecuteReader
If rdr.HasRows Then
While rdr.Read
arrName.Add(rdr("numb"))
For Each pno As String In arrName
MsgBox(pno)
Next
End While
End If
End sub
I want my output to be:
639057318820
639355514108
639056784959
but my code output is:
639057318820
639057318820
639355514108
639057318820
639355514108
639056784959
it seems like my code is reading is reading from the indexes 0 before reading the next index. help me guys?

Change
If rdr.HasRows Then
While rdr.Read
arrName.Add(rdr("numb"))
For Each pno As String In arrName
MsgBox(pno)
Next
End While
End If
to
If rdr.HasRows Then
While rdr.Read
arrName.Add(rdr("numb"))
End While
End If
For Each pno As String In arrName
MsgBox(pno)
Next

Related

Search function fail

I would like to search data in a textbox . Below is my code. I tried to search but nothing happen.
If Not Me.IsPostBack Then
Me.SearchPanelId()
End If
End Sub
Private Sub SearchPanelId()
Dim ConnectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand()
Dim sql As String = "SELECT panelid, panelname, paneltype FROM PANEL_TABLE"
If Not String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
sql += " WHERE panelid LIKE #panelid + '%'"
cmd.Parameters.AddWithValue("#panelid", TextBox1.Text.Trim())
End If
cmd.CommandText = sql
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub Search(sender As Object, e As EventArgs)
Me.SearchPanelId()
End Sub
Protected Sub OnPaging(sender As Object, e As GridViewPageEventArgs)
GridView1.PageIndex = e.NewPageIndex
Me.SearchPanelId()
End Sub
Do the validation before you start creating objects. You need to check if that datatype of the ID is valid. I guessed that this was an Integer type but check your database. If I am wrong and the datatype is .VarChar then see the second rendition. :-) The Like keyword does not make any sense with a numeric field.
Don't use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
A DataAdapter is not necessary. Just use the load method of the DataTable.
Private Sub SearchPanelId()
Dim IDValue As Integer
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) OrElse Not Integer.TryParse(TextBox1.Text.Trim, IDValue) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid = #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.Int).Value = IDValue
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
If Id is a .VarChar
Private Sub SearchPanelId()
Dim dt As New DataTable
If String.IsNullOrEmpty(TextBox1.Text.Trim()) Then
Return
End If
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT panelid, panelname, paneltype FROM PANEL_TABLE WHERE panelid Like #panelid", con)
cmd.Parameters.Add("#panelid", SqlDbType.VarChar).Value = TextBox1.Text.Trim() & "%"
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
GridView1.DataSource = dt
GridView1.DataBind()
End Sub

system.data.common.datarecordinternal in dropdownlist

After compiling I get an error
system.data.common.datarecordinternal in datalistview
It must get the data inside the database.
Dim connectionString As String = "Data Source=11.123.123.32;Initial Catalog=RESERVATION_SYSTEM;User Id=**;Password=***"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Using con As SqlConnection = New SqlConnection(connectionString)
Dim cmd As SqlCommand = New SqlCommand("Select [Room] FROM [RESERVATION_SYSTEM].[dbo].[LMO_RESERVATION_SYSTEM_ROOM]", con)
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
roomType.DataSource = rdr
roomType.DataBind()
roomType.DataTextField = "RESERVATION_SYSTEM"
End Using
roomType.Items.Insert(0, New ListItem("--Select Room --"))
End If
I solved my problem.
Based on my research this link 1 to solve my problem .
So before databind you need to include which column you will select in table.
roomType.DataTextField = "ROOM"
roomType.DataValueField = "ROOM"

ASP.net Session Variables aspnetdb login control

Hi people I am trying to carry a session variable for my login control which i am using to pass to pass to another page and display their details. I am using the aspNetDB. My username has been set to an integer as is connected to another database table displaying the users details below is my code:
Protected Sub Login1_LoggingIn(sender As Object, e As System.Web.UI.WebControls.LoginCancelEventArgs) Handles Login1.LoggingIn
Session("StaffNo") = Login1.UserName()
End Sub
The code is then being sent to my other page to display their details when loaded on a data grid but the session does not seem to be carrying:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Try
Dim Staff As String = CType(Session.Item("StaffNo"), String)
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim cmdstring As String = "SELECT * FROM [User] WHERE studentnum = #StaffNo"
conn = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdstring, conn)
cmd.Parameters.Add("#StaffNo", SqlDbType.Char).Value = Staff
conn.Open()
Dim myReader As SqlDataReader
myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
GridView1.DataSource = myReader
GridView1.DataBind()
conn.Close()
Catch ex As Exception
Response.Write("An error has occurred")
End Try
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Try
Dim cmdstring As String = "SELECT * FROM [User] WHERE studentnum = '"& Session("StaffNo").ToString & "' "
End Sub

Copying data from one table to another (along with some other data)

Is possible to transfer data from one table into an empty table along with a other data? Is it possible to do that with a single SQL statement? What I've tried so far produces no errors but the data from the original table is not transferred to the empty table.
I've include my code below and I'd appreciate any advice. I suspect there's a problem with the database connection, but I am still new to programming and I can't see the problem.
Imports System.Data.SqlClient
Public Class uploadSuccess
Inherits System.Web.UI.Page
Dim con As SqlConnection
Dim cmd As SqlCommand
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New SqlConnection("Data Source=127.0.0.1; User Id=user;Password=pass;Initial Catalog=catalog;")
con.Open()
cmd = con.CreateCommand()
cmd.Connection = con
Dim intCount As Int32
Dim getReceipt As Int32
Dim femtocellrow As Int32
Dim noreceipt As Int32
Dim username As String
Dim client As String
Dim comName As String
noreceipt = Session("recNo")
username = Session("username")
comName = Session("compName")
'Response.Write("noreceipt" & noreceipt)
cmd.CommandText = "SELECT COUNT(*) AS RETURNCOUNT FROM dbo.tempTable"
intCount = cmd.ExecuteScalar
' Response.Write("count " & intCount)
cmd.CommandText = "SELECT noDevices FROM dbo.Receipt WHERE receiptNo= #noreceipt"
cmd.Parameters.AddWithValue("#noreceipt", noreceipt)
getReceipt = cmd.ExecuteScalar
'Response.Write("receipt " & getReceipt)
cmd.CommandText = "SELECT COUNT(*) AS RETURNCOUNT FROM dbo.femtocell WHERE receiptNo= #norec"
cmd.Parameters.AddWithValue("#norec", noreceipt)
femtocellrow = cmd.ExecuteScalar
'Response.Write("femrow " & femtocellrow)
cmd.CommandText = "SELECT clientID FROM dbo.Receipt WHERE companyName=#comName"
cmd.Parameters.AddWithValue("#comName", comName)
client = cmd.ExecuteScalar
'Response.Write("client " & client)
con.Close()
Dim rowsAffected As Integer = 0
Dim myConnectionString As String = "Data Source=192.168.18.30; User Id=sa;Password=google;Initial Catalog=femtocell;"
Dim myConnection As New SqlConnection(myConnectionString)
If (femtocellrow < getReceipt) & (intCount < femtocellrow) Then
'Dim myQuery As String = "SELECT ([uploadID],[clientID],[receiptNo],[compName],[state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate],[compName]) INTO dbo.femtocell (username,client,noreceipt,comName,[State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]) FROM dbo.tempTable"
' Dim myQuery As String = "INSERT INTO dbo.femtocell ([uploadID],[clientID],[receiptNo],[compName],[state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate],[compName]) VALUES (SELECT 'username','client','noreceipt','comName',[State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]FROM dbo.tempTable"
Dim myQuery As String = "INSERT INTO dbo.femtocell ([state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate]) SELECT [State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]FROM dbo.tempTable"
Dim myCommand As New SqlCommand(myQuery, myConnection)
Try
myConnection.Open()
rowsAffected = myCommand.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
myConnection.Close()
End Try
Else
Dim message As String = "Number of devices submitted is invalid."
Dim sb As New System.Text.StringBuilder()
sb.Append("alert('")
sb.Append(message)
sb.Append("');")
ClientScript.RegisterOnSubmitStatement(Me.GetType(), "alert", sb.ToString())
End If
End Sub
End Class
Maybe one of these will help:
SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE
sqlauthority.com
copy all rows of a table to another table
stackoverflow.com
C# – Bulk copying data into MS SQL Server with DataTables
myadventuresincoding.wordpress.com

asp.net storing images

It's me your junior programmer extraodinaire
I'm trying to display an image from my database but when I try to extract the file it only contains 6 bytes of data which causes my program to throw an error. My instructor informed me that the file is too small for an image, leading me to believe that I'm not storing it properly. I would be most gracious if someone could identify any code that might cause this to happen.
this is my function grabbing/storing the file
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim _image As Byte()
_image = FileUpload1.FileBytes
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
cmd.Connection = conn
cmd.CommandText = "Insert INTO mrg_Image(Image, UserId) VALUES('#image', #id)"
cmd.Parameters.AddWithValue("#image", FileUpload1.FileBytes)
cmd.Parameters.AddWithValue("#id", 4)
conn.Open()
dr = cmd.ExecuteReader
conn.Close()
'FileUpload1.SaveAs()
End Sub
conn.Open()
file_bytes is the variable that contains 6 bytes as oppose to a thousand+ which an image should have
Dim file_bytes As Byte() = cmd.ExecuteScalar()
Dim file_bytes_memory_stream As New System.IO.MemoryStream(file_bytes)
Dim file_bytes_stream As System.IO.Stream = DirectCast(file_bytes_memory_stream, System.IO.Stream)
Dim the_image As New System.Drawing.Bitmap(file_bytes_stream)
context.Response.ContentType = "image/jpg"
the_image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
conn.Close()
End Sub
Try replacing '#image' with #image.
Also replace ExecuteReader with ExecuteNonQuery.
I wasn't aware of the FileBytes property, I've always done it so...
Dim _image(FileUpload1.PostedFile.InputStream.Length) As Byte
FileUpload1.PostedFile.InputStream.Read(_image, 0, _image.Length)
Try this
cmd.CommandText = "Insert INTO mrg_Image(Image, UserId) VALUES(#image, #id)"
cmd.Parameters.Add("#image", SqlDbType.Image)
cmd.Parameters("#image") = FileUpload1.FileBytes
cmd.Parameters.AddWithValue("#id", 4)
Edit
Removed ";" forgot this was vb
Edit2
Changed [] to (). again forgot my VB

Resources