Avoiding Cross Side Scripting in asp.net - sql

I am currently coding a registration module. Basically, it's a registration module that takes the user info from asp.net site and sends them to the SQL server. I made significant changes but I still have XSS issues when I scan it with acunetix. The registration module works just fine but I wanted to avoid XSS. Because it's clearly vulnerable and it did not pass the acunetix scan.
The last code that I came up with is below. It's a button click event.
Dim connQuery As String = "Data Source=myserver;Initial Catalog=mydatabase;Integrated Security=True"
Dim cs As SqlConnection = New SqlConnection(connQuery)
Dim da As SqlDataAdapter = New SqlDataAdapter()
Dim table As String = "[mydatabase].[dbo].[users]"
Dim query As String = "INSERT INTO " & table & "(passwd, FName, LName, Organization, TelNo, FaxNo, Title, Email, User_type, GroupID, Activated, request_num, FirstLogin, LastLogin, IsLoggedin, IsOutsideInv, WI, study_type) VALUES (#passwd, #FName, #LName, #Organization, #TelNo, #FaxNo, #Title, #Email, #User_type, #GroupID, #Activated, #request_num, #FirstLogin, #LastLogin, #IsLoggedin, #IsOutsideInv, #WI, #study_type)"
Try
da.InsertCommand = New SqlCommand(query, cs)
' da.InsertCommand.Parameters.Add("#passwd", SqlDbType.NVarChar).Value = txtPassword.Text
da.InsertCommand.Parameters.Add("#passwd", SqlDbType.NVarChar).Value = encode(txtPassword.Text)
da.InsertCommand.Parameters.Add("#FName", SqlDbType.NVarChar).Value = txtFirstName.Text
da.InsertCommand.Parameters.Add("#LName", SqlDbType.NVarChar).Value = txtLastName.Text
da.InsertCommand.Parameters.Add("#Organization", SqlDbType.NVarChar).Value = txtOrg.Text
da.InsertCommand.Parameters.Add("#TelNo", SqlDbType.NVarChar).Value = txtPhone.Text
da.InsertCommand.Parameters.Add("#FaxNo", SqlDbType.NVarChar).Value = txtFax.Text
da.InsertCommand.Parameters.Add("#Title", SqlDbType.NVarChar).Value = txtTitle.Text
da.InsertCommand.Parameters.Add("#Email", SqlDbType.NVarChar).Value = txtEmail.Text
da.InsertCommand.Parameters.Add("#User_type", SqlDbType.Int).Value = 0
da.InsertCommand.Parameters.Add("#GroupID", SqlDbType.NVarChar).Value = 0
da.InsertCommand.Parameters.Add("#Activated", SqlDbType.Bit).Value = 0
da.InsertCommand.Parameters.Add("#request_num", SqlDbType.Int).Value = 0
da.InsertCommand.Parameters.Add("#FirstLogin", SqlDbType.DateTime).Value = DateAndTime.Now
da.InsertCommand.Parameters.Add("#LastLogin", SqlDbType.NVarChar).Value = DateAndTime.Now
da.InsertCommand.Parameters.Add("#IsLoggedin", SqlDbType.Bit).Value = 0
da.InsertCommand.Parameters.Add("#IsOutsideInv", SqlDbType.NVarChar).Value = 0
da.InsertCommand.Parameters.Add("#WI", SqlDbType.NVarChar).Value = txtInves.Text
da.InsertCommand.Parameters.Add("#study_type", SqlDbType.NVarChar).Value = 0
cs.Open()
da.InsertCommand.ExecuteNonQuery()
cs.Close()
Catch ex As Exception
Labelmessage.Text = "Error while adding record to the database ==> " & ex.Message.ToString()
Finally
cs.Close()
End Try
What would be the ideal way to pass this scan? I would appreciate any help.

Related

ExecuteNonQuery returns -1 (incorrectly)

I inherited an old VB Website the uses ExecuteNonQuery to modify passwords. In our production environment, sql server 2008 R2, I've had recent reports of broken functionality. It turns out the ExecuteNonQuery is returning -1 when in fact the data is getting updated (a single row). When I copied the data to our dev environment, the rows affected is 1 as expected. We have a different service packs applied (4XXX vs 6XXX) and I wonder if this is the issue? I modified the code to use ExecuteScalar to inspect the RowCount, and this is working. But I shouldn't have to do so. Any insight? I have now idea how long this has been broken.
Here's the original code, that returns -1 erroneously. It is not calling a stored procedure and there are no triggers involved.
Dim cmd As SqlCommand = New SqlCommand("UPDATE UserMaster " & _
" SET Password = #Password, LastPasswordChangedDate = #LastPasswordChangedDate " & _
" WHERE Username = #UserName AND ApplicationName = #ApplicationName ", conn)
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 255).Value = CreateHash(newPwd)
cmd.Parameters.Add("#LastPasswordChangedDate", SqlDbType.DateTime).Value = DateTime.Now
cmd.Parameters.Add("#Username", SqlDbType.VarChar, 255).Value = username.TrimEnd
cmd.Parameters.Add("#ApplicationName", SqlDbType.VarChar, 255).Value = Left(pApplicationName, 1)
Dim rowsAffected As Integer = 0
Try
conn.Open()
rowsAffected = cmd.ExecuteNonQuery()
This code returns a 1 as expected:
Dim cmd As SqlCommand = New SqlCommand("UPDATE UserMaster " & _
" SET Password = #Password, LastPasswordChangedDate = #LastPasswordChangedDate " & _
" WHERE Username = #UserName AND ApplicationName = #ApplicationName ; select ##rowcount", conn)
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 255).Value = CreateHash(newPwd)
cmd.Parameters.Add("#LastPasswordChangedDate", SqlDbType.DateTime).Value = DateTime.Now
cmd.Parameters.Add("#Username", SqlDbType.VarChar, 255).Value = username.TrimEnd
cmd.Parameters.Add("#ApplicationName", SqlDbType.VarChar, 255).Value = Left(pApplicationName, 1)
Dim rowsAffected As Integer = 0
Try
conn.Open()
rowsAffected = CType(cmd.ExecuteScalar(), Integer)
ExceuteNonQuery returns -1 for all stored procedures as per the Msdn documentation.
It will return the updated records' number only in case of a statement.

How to stop loop

I have a problem with Do until loop. When the record successfully saved and message-box appeared, after clicking the OK button it just shows the message-box and repeat it endlessly. I don't know what's the code for that. Please help.
MySqlConn.Open()
Dim last, midd, first, age, occu, phone As MySqlDataReader
Dim cmd1, cmd2, cmd3, cmd4, cmd5, cmd6, cmd7, cmd8, cmd9, cmd10, cmd11 As New MySqlCommand
Dim query1, query2, query3, query4, query5, query6, query7, query8, query9, query10, query11 As String
'lastname query
query1 = "SELECT * FROM newpatient WHERE Lastname ='" & txtLastname.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
last = cmd1.ExecuteReader
'first query
query2 = "SELECT * FROM newpatient WHERE Firstname ='" & txtFirstname.Text & "'"
cmd2 = New MySqlCommand(query2, MySqlConn)
last.Close()
first = cmd2.ExecuteReader
'middle query
query3 = "SELECT * FROM newpatient WHERE Middlename ='" & txtMiddlename.Text & "'"
cmd3 = New MySqlCommand(query3, MySqlConn)
first.Close()
midd = cmd3.ExecuteReader
'age query
query4 = "SELECT * FROM newpatient WHERE Age ='" & txtAge.Text & "'"
cmd4 = New MySqlCommand(query4, MySqlConn)
midd.Close()
age = cmd4.ExecuteReader
'gender query
query5 = "SELECT * FROM newpatient WHERE Occupation ='" & txtOccupation.Text & "'"
cmd5 = New MySqlCommand(query5, MySqlConn)
age.Close()
occu = cmd5.ExecuteReader
'phone query
query6 = "SELECT * FROM newpatient WHERE Mobile_Number ='" & txtMobileNumber.Text & "'"
cmd6 = New MySqlCommand(query6, MySqlConn)
occu.Close()
phone = cmd6.ExecuteReader
Do While last.HasRows = 0 And first.HasRows = 0 And midd.HasRows = 0 And occu.HasRows = 0 And phone.HasRows = 0 And age.HasRows = 0
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO newpatient (ID, Lastname, Firstname, Middlename, Age, Mobile_Number, Gender, Address, Occupation, Month, Day, Year )" &
"VALUES ('{0}' ,'{1}' ,'{2}' ,'{3}' ,'{4}' ,'{5}' , '{6}', '{7}', '{8}', '{9}', '{10}', '{11}' )",
txtID.Text,
txtLastname.Text,
txtFirstname.Text,
txtMiddlename.Text,
txtAge.Text,
txtMobileNumber.Text,
cmbGender.SelectedItem,
txtAddress.Text,
txtOccupation.Text,
cmbMonth.SelectedItem,
cmbDay.SelectedItem,
cmbYear.SelectedItem)
phone.Close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
'AUTO GENERATE RANDOM IDs
Dim random As New Random
Dim id As Integer
id = (random.Next(100000000, 1000000000))
txtID.Text = id
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
txtLastname.Select()
Else
MsgBox("Saving record failed.", MsgBoxStyle.Critical, "Failed")
'AUTO GENERATE RANDOM IDs
Dim random As New Random
Dim id As Integer
id = (random.Next(100000000, 1000000000))
txtID.Text = id
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
txtLastname.Select()
End If
Loop
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
MsgBox("Patient has already registered!", MsgBoxStyle.Critical, "Already registered")
MySqlConn.close()
To stop the loop requires a call to Exit, like so:
Exit Do
Having said that, you should never just call Exit without requiring a condition to be met, or you can encounter unexpected behavior.
But you've got much larger problems here. I'm going to list them out quickly and include a quick pseudocode suggestion (as in I've never used MySql in .Net, so not at all familiar with the API, so this code WILL need modified before it would work)
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = "INSERT INTO newpatient (ID, Lastname, Firstname, Middlename, Age, Mobile_Number, Gender, Address, Occupation, Month, Day, Year )" &
"VALUES (:ID, :Lastname, :Firstname, :Middlename, :Age, :Mobile_Number, :Gender, :Address, :Occupation, :Month, :Day, :Year)"
cmd.Parameters.Add(new MySqlParameter(":ID", txtID.Text))
cmd.Parameters.Add(new MySqlParameter(":Lastname", txtLastname.Text))
cmd.Parameters.Add(new MySqlParameter(":Firstname", txtFirstname.Text))
cmd.Parameters.Add(new MySqlParameter(":Middlename", txtMiddlename.Text))
cmd.Parameters.Add(new MySqlParameter(":Age", txtAge.Text))
cmd.Parameters.Add(new MySqlParameter(":Mobile_Number", txtMobileNumber.Text))
cmd.Parameters.Add(new MySqlParameter(":Gender", cmbGender.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Address", txtAddress.Text))
cmd.Parameters.Add(new MySqlParameter(":Occupation", txtOccupation.Text))
cmd.Parameters.Add(new MySqlParameter(":Month", cmbMonth.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Day", cmbDay.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Year", cmbYear.SelectedItem))
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows = 1 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
Else
If affectedrows = 0 Then
'Most likely the record already existed, call an update here and if you get 1 result, the record existed and you just saved changes
MsgBox("Patient has already registered!", MsgBoxStyle.Critical, "Already registered")
'You could change the above to a Yes/No question about updating the record and have the result in an if to update the record at the user's discretion.
cmd = MySqlConn.CreateCommand
cmd.CommandText = "UPDATE newpatient " &
"SET Lastname = :Lastname, Firstname = :Firstname, Middlename = :Middlename, Age = :Age, Mobile_Number = :Mobile_Number, " &
" Gender = :Gender, Address = :Address, Occupation = :Occupation, Month = :Month, Day = :Day, Year = :Year " &
"WHERE ID = :ID"
cmd.Parameters.Add(new MySqlParameter(":ID", txtID.Text))
cmd.Parameters.Add(new MySqlParameter(":Lastname", txtLastname.Text))
cmd.Parameters.Add(new MySqlParameter(":Firstname", txtFirstname.Text))
cmd.Parameters.Add(new MySqlParameter(":Middlename", txtMiddlename.Text))
cmd.Parameters.Add(new MySqlParameter(":Age", txtAge.Text))
cmd.Parameters.Add(new MySqlParameter(":Mobile_Number", txtMobileNumber.Text))
cmd.Parameters.Add(new MySqlParameter(":Gender", cmbGender.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Address", txtAddress.Text))
cmd.Parameters.Add(new MySqlParameter(":Occupation", txtOccupation.Text))
cmd.Parameters.Add(new MySqlParameter(":Month", cmbMonth.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Day", cmbDay.SelectedItem))
cmd.Parameters.Add(new MySqlParameter(":Year", cmbYear.SelectedItem))
affectedrows = cmd.ExecuteNonQuery()
If affectedrows = 1 Then
MsgBox("Record successfully saved!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Saving record failed.", MsgBoxStyle.Critical, "Failed")
End If
Else
'Should never get here. We covered 0 and 1 in the other two logic branches.
'In this small demo, handling when more than 1 record gets updated is out of scope.
End If
End If
'CLEARS TEXTBOXES
txtMobileNumber.Text = ""
txtLastname.Text = ""
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtAge.Text = 0
cmbGender.SelectedItem = ""
cmbDay.SelectedItem = ""
cmbMonth.SelectedItem = ""
cmbYear.SelectedItem = 0
txtAddress.Text = ""
txtOccupation.Text = ""
txtLastname.Select()
MySqlConn.close()
Never build queries from strings where you rely on a user for some of those strings. This leaves you vulnerable to SQL injection attacks (try putting a name with an apostrophe in it in one of the name fields and watch the flurry of errors. Then realize someone with malicious intentions could do serious damage to your database if you don't sanitize your inputs) Always parameterize your queries wherever possible!!
Don't repeat yourself! (AKA the DRY principle) If you find yourself copying/pasting the same block of code from place to place, that means you're doing something wrong. In this case, it was that you got stuck on the idea that you HAD to have a loop, and to make sure you're input fields were cleared, you just copied the code to clear them to 3 different places in the codepath. If you find that you NEED to run the same code repeatedly throughout your programs codepath, then generalize it and put it in a function. Your eyes and the eyes of the next person to read/maintain your code will appreciate it!
You need some more knowledge/experience with SQL, and that's ok, everyone had to start somewhere. In the sample, I removed ALL of your select queries in favor of trying ONE insert query and branching the logic based on the result of that 1 query. Much easier to read/maintain. Also, Identity values should be handle BY your sql instance, not in code. You generally want them used sequentially to avoid collisions and you don't want them modified by/visible to end users. Correcting the properties of the ID column allows removal of the random generation code. Just remember that when you insert into a table with an identity column that you don't need to include the identity column in your INSERT statement (SQL will fill that column for you)

Why do I get "Syntax error in INSERT INTO statement"?

Private Sub Save_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandText = CommandType.Text
If Me.txt_Forename.Tag = 0 Then
sSQL = "INSERT INTO PlayerDatabase ( Age_Group, Surname, Forename, Rating, DOB, Address, Email, Position, Foot, Mins_Played, Goals, Assists, Yellow_Cards, Red_Cards)"
sSQL = sSQL & " VALUES(#Age_Group, #Surname, #Forename, #Rating, #DOB, #Address, #Email, #Position, #Foot, #Mins_Played, #Goals, #Assists, #Yellow_Cards, #Red_Cards)"
Else
sSQL = "UPDATE PlayerDatabase set Age_Group = #Age_Group, Surname = #Surname, Forename = #Forename, Rating = #Rating, DOB = #DOB, Address = #Address, Email = #Email, Position = #Position, Foot = #Foot, Mins_Played = #Mins_Played, Goals = #Goals, Assists = #Assists, Yellow_Cards = #Yellow_Cards, Red_Cards = #Red_Cards WHERE ID = #id"
cmd.CommandText = sSQL
End If
cmd.Parameters.Add("#Surname", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Surname.Text)) > 0, Me.txt_Surname.Text, DBNull.Value)
cmd.Parameters.Add("#Forename", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Forename.Text)) > 0, Me.txt_Forename.Text, DBNull.Value)
cmd.Parameters.Add("#DOB", OleDbType.Date).Value = Me.dtp_DOB.Text
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = Me.txt_Address.Text
cmd.Parameters.Add("#Age_Group", OleDbType.VarChar).Value = Me.cb_AgeGroup.Text
cmd.Parameters.Add("#Rating", OleDbType.VarChar).Value = Me.cb_Rating.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = Me.txt_Email.Text
cmd.Parameters.Add("#Position", OleDbType.VarChar).Value = Me.cb_Position.Text
cmd.Parameters.Add("#Foot", OleDbType.VarChar).Value = Me.cb_Foot.Text
cmd.Parameters.Add("#Mins_Played", OleDbType.VarChar).Value = Me.nup_MinsPlayed.Text
cmd.Parameters.Add("#Goals", OleDbType.VarChar).Value = Me.nup_Goals.Text
cmd.Parameters.Add("#Assists", OleDbType.VarChar).Value = Me.nup_Assists.Text
cmd.Parameters.Add("#Yellow_Cards", OleDbType.VarChar).Value = Me.nup_YellowCards.Text
cmd.Parameters.Add("#Red_Cards", OleDbType.VarChar).Value = Me.nup_RedCards.Text
cmd.Parameters.Add("#ID", OleDbType.Numeric).Value = Me.txt_Forename.Tag
cmd.ExecuteNonQuery()
If Me.txt_Forename.Tag = 0 Then
cmd.CommandText = "Select ##Identity"
Me.txt_Forename.Tag = cmd.ExecuteScalar()
End If
MsgBox("Data has been saved.")
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
Not sure what I'm doing wrong here. This is a adding to an Access database from various textboxes, comboboxes etc. This procedure runs when a button is pressed on a form that has the inputs. I'm a beginner at vb.net and programming in general so if it's something obvious I apologise.
Thanks
The word POSITION is reserved in MS-Access Jet Sql. This is the reason of the SYNTAX ERROR.
If you want to use it as a name for a column or for a table you need to put it between square brackets
sSQL = "INSERT INTO PlayerDatabase ( Age_Group, Surname, Forename, Rating, DOB, " & _
"Address, Email, [Position], Foot, Mins_Played, Goals, Assists, Yellow_Cards, Red_Cards)"
....
sSQL = "UPDATE PlayerDatabase set Age_Group = #Age_Group, Surname = #Surname, " & _
"Forename = #Forename, Rating = #Rating, DOB = #DOB, Address = #Address, " & _
"Email = #Email, [Position] = #Position, Foot = #Foot, Mins_Played = #Mins_Played, " & _
"Goals = #Goals, Assists = #Assists, Yellow_Cards = #Yellow_Cards, " & _
"Red_Cards = #Red_Cards WHERE ID = #id"
A part from this you have another problem. OleDb doesn't recognize the parameters by their names. Usually you should use a question mark instead of a name, but Access allows this probably for some kind of portability toward its big cousin Sql Server. In any case you should add the parameters in the OleDbCommand collection in the same order in which the named placeholders appears in your query. So you need this order:
cmd.Parameters.Add("#Age_Group", OleDbType.VarChar).Value = Me.cb_AgeGroup.Text
cmd.Parameters.Add("#Surname", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Surname.Text)) > 0, Me.txt_Surname.Text, DBNull.Value)
cmd.Parameters.Add("#Forename", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txt_Forename.Text)) > 0, Me.txt_Forename.Text, DBNull.Value)
cmd.Parameters.Add("#Rating", OleDbType.VarChar).Value = Me.cb_Rating.Text
cmd.Parameters.Add("#DOB", OleDbType.Date).Value = Me.dtp_DOB.Text
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = Me.txt_Address.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = Me.txt_Email.Text
cmd.Parameters.Add("#Position", OleDbType.VarChar).Value = Me.cb_Position.Text
cmd.Parameters.Add("#Foot", OleDbType.VarChar).Value = Me.cb_Foot.Text
cmd.Parameters.Add("#Mins_Played", OleDbType.VarChar).Value = Me.nup_MinsPlayed.Text
cmd.Parameters.Add("#Goals", OleDbType.VarChar).Value = Me.nup_Goals.Text
cmd.Parameters.Add("#Assists", OleDbType.VarChar).Value = Me.nup_Assists.Text
cmd.Parameters.Add("#Yellow_Cards", OleDbType.VarChar).Value = Me.nup_YellowCards.Text
cmd.Parameters.Add("#Red_Cards", OleDbType.VarChar).Value = Me.nup_RedCards.Text
and this last parameter should be added only if you have the UPDATE path not for the INSERT. (Assuming the ID column to be an AutoIncrement one)
If Me.txt_Forename.Tag <> 0 Then
cmd.Parameters.Add("#ID", OleDbType.Numeric).Value = Me.txt_Forename.Tag
End If
Also another problem at the end when you try to read the ##IDENTITY value. Using the same command is fine, but you need to clear the parameters collection
If Me.txt_Forename.Tag = 0 Then
cmd.Parameters.Clear()
cmd.CommandText = "Select ##Identity"
Me.txt_Forename.Tag = cmd.ExecuteScalar()
End If

Populating datagrid1.view with a SQL Server stored procedure

I got a stored procedure in SQL Server I created some inner joins and now how will I populate my datagrid using that stored procedure.
Here is my code that is not working
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "OfficeEquipmentProfile"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlconn
sqlconn.Open()
sAdapter = New SqlDataAdapter(cmd)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet
sAdapter.Fill(sDs, "tblOfficeEquipmentProfile")
sAdapter.Fill(sDs, "tblDepartment")
sAdapter.Fill(sDs, "tblLocation")
sAdapter.Fill(sDs, "tblOfficeEquipmentCategory")
sAdapter.Fill(sDs, "tblApplication")
sAdapter.Fill(sDs, "tblApplicationLicense")
sAdapter.Fill(sDs, "tblEquipmentApplication")
sAdapter.Fill(sDs, "tblOfficeEquipmentBrand")
sAdapter.Fill(sDs, "tblOfficeEquipmentModel")
sAdapter.Fill(sDs, "tblOfficeEquipmentServiceOrder")
sAdapter.Fill(sDs, "tblOfficeEquipmentPMplan")
sTable = sDs.Tables("tblOfficeEquipmentProfile")
sTable = sDs.Tables("tblDepartment")
sTable = sDs.Tables("tblLocation")
sTable = sDs.Tables("tblOfficeEquipmentCategory")
sTable = sDs.Tables("tblApplication")
sTable = sDs.Tables("tblApplicationLicense")
sTable = sDs.Tables("tblEquipmentApplication")
sTable = sDs.Tables("tblOfficeEquipmentBrand")
sTable = sDs.Tables("tblOfficeEquipmentServiceOrder")
sTable = sDs.Tables("tblOfficeEquipmentPMplan")
DataGrid1.DataSource = sDs.Tables("tblOfficeEquipmentProfile, tblDepartment, tblLocation, tblOfficeEquipmentCategory, tblApplication,tblApplicationLicense, tblEquipmentApplication, tblOfficeEquipmentBrand, tblOfficeEquipmentServiceOrder,tblEquipmentPMplan")
DataGrid1.ReadOnly = True
'Button1.Enabled = False
'DataGrid1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
reader = cmd.ExecuteReader()
sqlconn.Close()
I just want to display records from the database
As you are returning columns from different tables and not multiple tables then you just need this code.
Dim Command As SqlCommand = New SqlCommand()
Command.Connection = Connection
Command.CommandText = "OfficeEquipmentProfile"
Command.CommandType = CommandType.StoredProcedure
Dim sAdapter As SqlDataAdapter = New SqlDataAdapter(Command)
Dim DataSet As DataSet = New DataSet(Command.CommandText)
sAdapter.Fill(DataSet)
DataGrid1.DataSource = DataSet.Tables(0)
Try with this code
Dim cmd As New SqlCommand
cmd.CommandText = "OfficeEquipmentProfile"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlconn
sqlconn.Open()
sAdapter = New SqlDataAdapter(cmd)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet
sAdapter.Fill(sDs)
DataGrid1.DataSource = sDs
The storedprocedure return one or more tables, but you don't need to call a Fill for each table. One is enough. Then assign the whole Dataset to the Datasource or, if you return more than one table and need a specific table
DataGrid1.DataSource = sDs
DataGrid1.DataMember = "tablename"
Try
If con.State = ConnectionState.Open Then con.Close()
con.Open()
Dim dset As New DataSet
Dim dbind As New BindingSource
Dim strquery As String
strquery = "SELECT prod_code, prod_no, prod_suffix, prod_lvl, customer, model, family, company_code, company_name, company_address, running_no, template_code FROM products_tbl WHERE template_code = 'n'and company_code = 'YTPL' and prod_no = '" & txt_product.Text & "' and prod_suffix = '" & txt_suffix.Text & "' and prod_lvl = '" & txt_level.Text & "'"
Dim adap As New SqlDataAdapter(strquery, con)
dset = New DataSet
adap.Fill(dset)
dbind.DataSource = dset.Tables(0)
dg.DataSource = dbind
Catch ex As Exception
MsgBox("Trace No 3: System Error or Data Error!" + Chr(13) + ex.Message + Chr(13) + "Please Contact Your System Administrator!", vbInformation, "Message")
End Try

SQL Server CE query having no effect?

I'm attempting to insert rows into a SQL Server CE database, and it's returning that 1 row is affected, there's no exception, and no syntax error in the query as far as I can see - but it's having no effect, when I look in the table from the Database Explorer.
If I run a query through VS, everything works fine. There's no connection problem as far as I can tell... what am I doing wrong here?
Here's the code, though it probably doesn't make a difference:
Using conn As New SqlCeConnection(My.Settings.DietSafetyCheckerReportsConnectionString)
conn.Open()
Using cmd As SqlCeCommand = conn.CreateCommand()
cmd.CommandText = "INSERT INTO Reports(PatientID, PreparedBy, PreparedFor, WeightInKilos, HeightInMeters, Age, PercentBodyFat, ElbowMeasurementInCentimeters, ReportDate, Gender) " &
"VALUES(#pid, #pby, #pfor, #weight, #height, #age, #bodyfat, #elbow, #rdate, #gender);"
cmd.Parameters.Add("#pid", SqlDbType.NVarChar, 100).Value = Me.PatientID
cmd.Parameters.Add("#pby", SqlDbType.NVarChar, 100).Value = Me.PreparedBy
cmd.Parameters.Add("#pfor", SqlDbType.NVarChar, 100).Value = Me.PreparedFor
cmd.Parameters.Add("#weight", SqlDbType.Float).Value = Me.WeightInKilos
cmd.Parameters.Add("#height", SqlDbType.Float).Value = Me.HeightInMeters
cmd.Parameters.Add("#age", SqlDbType.TinyInt).Value = Me.Age
cmd.Parameters.Add("#bodyfat", SqlDbType.Float, 100).Value = Me.PercentBodyFat
cmd.Parameters.Add("#elbow", SqlDbType.TinyInt, 100).Value = Me.ElbowMeasurementInCentimeters
cmd.Parameters.Add("#rdate", SqlDbType.DateTime).Value = Me.ReportDate
cmd.Parameters.Add("#gender", SqlDbType.TinyInt, 100).Value = Me.Gender
If cmd.ExecuteNonQuery() <> 1 Then Throw New ApplicationException("Failed to insert row into databse.")
End Using
conn.Close()
End Using
(By the way, this also doesn't work:
Using da As New SqlCeDataAdapter("SELECT * FROM Reports", conn)
Dim ds As New DietSafetyCheckerReportsDataSet()
Dim dt As DietSafetyCheckerReportsDataSet.ReportsDataTable
da.Fill(ds)
dt = DirectCast(ds.Tables("Reports"), DietSafetyCheckerReportsDataSet.ReportsDataTable)
Dim dr As DietSafetyCheckerReportsDataSet.ReportsRow = dt.NewReportsRow()
dr.Age = Me.Age
dr.ElbowMeasurementInCentimeters = Me.ElbowMeasurementInCentimeters
dr.Gender = Me.Gender
dr.HeightInMeters = Me.HeightInMeters
dr.PatientID = Me.PatientID
dr.PercentBodyFat = Me.PercentBodyFat
dr.PreparedBy = Me.PreparedBy
dr.PreparedFor = Me.PreparedFor
dr.ReportDate = Me.ReportDate
dr.WeightInKilos = Me.WeightInKilos
dt.Rows.Add(dr)
da.Update(ds)
End Using
)
Look in your bin/debug folder, you probably have more copies of the same database file
My suggestion is that you turned off autocommit mode on server (which is on by default) or on connection settings, so you need to commit your transaction manually. Take a look here for more info.