String Comparison in ASP.NET - asp.net

I was fetching data from database using DataReader object, but if condition is not getting true in the following code.
I'm trying to make student login page. And I'm posting the sample code where I'm getting the problem.
Dim cnn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim str3, str4 As String
Dim cmd As New SqlCommand
cmd.CommandText = "Select Name,password from Student"
cmd.Connection = cnn
cnn.Open()
Dim dr = cmd.ExecuteReader
While dr.Read
str3 = dr.Item(0)
str4 = dr.Item(1)
If (String.Equals(str3, TextBox1.Text) And String.Equals(str4, TextBox1.Text)) Then
Response.Write("Login")
Else
Response.Write("NotLogin")
End If
Response.Write(str3 & " " & str4 & "<br>")
Response.Write(TextBox1.Text & " " & TextBox2.Text & "<br>")
End While
End Sub
I have added Response.Write statement to check whether the values are correctly fetched from database or not. It turns out that the values were correctly fetched from database and even the value of those textboxes are equal to dr.Item(0) and dr.Item(1), but somehow the If statement is not working.

Related

This website can not be accessed,The connection has been reset? asp.net using vb.net

When I try to insert into databases, the following message shows up:
This website can not be accessed
The connection has been reset.
try:
Check the connection.
Check the proxy server and firewall.
Run Windows Network Diagnostic Data
my code is:
Protected Sub btnYes_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnYes.Click
Dim bday As String = DropDownList11.SelectedItem.ToString & "/" & DropDownList10.SelectedItem.ToString & "/" & DropDownList12.SelectedItem.ToString
Try
Dim conn1 As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\pc1\Desktop\WebApplication1111\WebApplication1\App_Data\StudentRegistration.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
Dim cmd As New SqlCommand("insert into students values(#std_nn, #std_sn, #std_fn, #stdsecn, #std_midn, #std_ln, #std_gndr, #std_bday, #std_cbirth, #std_ident, #stdmstatus, #std_mail, #std_phone, #std_ppic, #std_rstatus, #std_spec, #std_twjavg, #std_twjtype)", conn1)
Dim affectedrow As Integer
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#std_nn", Session("studentno").ToString)
cmd.Parameters.AddWithValue("#std_fn", TextBox2.Text)
cmd.Parameters.AddWithValue("#stdsecn", TextBox3.Text)
cmd.Parameters.AddWithValue("#std_midn", TextBox4.Text)
cmd.Parameters.AddWithValue("#std_ln", TextBox5.Text)
cmd.Parameters.AddWithValue("#std_gndr", DropDownList1.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#std_bday", bday)
cmd.Parameters.AddWithValue("#std_cbirth", TextBox6.Text)
cmd.Parameters.AddWithValue("#std_ident", TextBox7.Text)
cmd.Parameters.AddWithValue("#stdmstatus", DropDownList2.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#std_mail", TextBox8.Text)
cmd.Parameters.AddWithValue("#std_phone", TextBox9.Text)
cmd.Parameters.AddWithValue("#std_ppic", Image1.ImageUrl.ToString)
cmd.Parameters.AddWithValue("#std_rstatus", "waiting")
cmd.Parameters.AddWithValue("#std_spec", DBNull.Value)
cmd.Parameters.AddWithValue("#std_twjavg", TextBox10.Text)
cmd.Parameters.AddWithValue("#std_twjtype", DropDownList3.SelectedItem.ToString)
If conn1.State = ConnectionState.Closed Then
conn1.Open()
affectedrow = cmd.ExecuteNonQuery()
End If
conn1.Close()
If affectedrow > 0 Then
add_subjects()
add_attachments()
Label1.Text = "done"
Response.Redirect("Stdinfo.aspx")
End If
Catch ex As Exception
Label1.Text = "error"
End Try
End Sub

VB ASP Array prevent multi reading

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

Getting error for Data Reader in vb.net

Im facing the error when execute the data reader command in vb.net. it throw handling. This field like when you enter employee id in textbox then it will capture in database for other field name,department.
here is my code
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String =ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Dim sqlQuery As String = "SELECT * hr_record WHERE Emplid='" & txt1.Text & "'"
Using sqlConn As New MySqlConnection(strConnectionString)
Using sqlComm As New MySqlCommand()
With sqlComm
.CommandText = sqlQuery
End With
Try
sqlConn.Open()
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
TextBox2.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
Try to change your select query like
Dim sqlQuery As String = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
Note:- Cannot use code like that in Page_Load.Try to make one Function and call that function from Page_Load and always use Parameterized query.
Updated answer:
Page_Load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
DataBind()
End Sub
Outside Method:
Public Sub DataBind()
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New MySqlConnection(sConnection)
Con.Open()
Using Com As New MySqlCommand("SELECT * from hr_record WHERE Emplid='"txt1.Text
"'", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txt1.Text = RDR.Item("Emplid").ToString()
TextBox1.Text = RDR.Item("Nama").ToString()
TextBox2.Text = RDR.Item("DeptDesc").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
End Sub
Note:Try to implement your logic like that and also modified as per your requirements.
Hope it works.
You try to get Emplid in page load,but it's still nothing you should use button to check if Emplid exist
Thanks to all thanks helping me..finally this code it works thanks to all .
this the code will be function
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Using sqlConn As New MySqlConnection(strConnectionString)
sqlConn.Open()
Using sqlComm As New MySqlCommand()
sqlComm.Connection = sqlConn
With sqlComm
.CommandText = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
End With
Try
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
txtdep.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
sqlConn.Close()
End Using
End Using
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

what is the problem in this query it will delete all records of table !

Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
For Each myRow As GridViewRow In GridView3.Rows
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE * FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
Next
GridView3.DataBind()
End Sub
I'm not sure why you think that will delete everything in the table, as I'm fairly certain it will not even execute. DELETE does not require any columns or * to be specified. It should just be DELETE FROM hotels WHERE [etc, etc].
Also, you should seriously consider giving this article a read: How To: Protect From SQL Injection in ASP.NET. Especially "Step 3. Use Parameters with Dynamic SQL", which detail how you could change your code to prevent SQL injection.
I believe what you are looking for is this:
Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
Dim myRow As GridViewRow = DirectCast((System.Web.UI.Control)(sender)).NamingContainer, GridViewRow)
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
GridView3.DataBind()
End Sub
The syntax may be off I'm not too familiar with VB. As well it would be better to pass the ID of the hotel record in the e.CommandArgument thus you would not have to retrieve it from a label on the page. It is deleting all your records because you are looping through all your rows in the grid view and deleting each record.

Resources