webform multi column single row SQL Server result to vb variables - asp.net

Ive looked through a few questions on here today and think I'm going round in circles.
My webform has a number of elements including username which is a drop down list (populated by a SQL statement)
On submit of the form i would like the code behind aspx.vb file run a select top 1 query and return a single row of data with 4 columns.
The returned SQL query result 4 columns would only be used later in the aspx.vb file so i want to assign each of the columns to a variable. I'm struggling with this task and assigning the variable the column result from the query.
Protected Sub submitbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitbtn.Click
Dim connString1 As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString
Dim conn As New SqlConnection(connString1)
Dim sql1 As String = ""
Dim col1h As String = ""
Dim col2r As String = ""
Dim col3title As String = ""
Dim col4UQN As String = ""
sql1 = "SELECT TOP 1 col1h,col2r,col3title, col4UNQ from tblDistinctUserOHR where colID_Username= '" + username + "' "
Dim cmd1 As New SqlCommand(sql1, conn)
'open the connection
'run the sql
'the result will always be found but in case its not some form of safety catch (the variables stay as empty strings
'assign the results to the variables
'close connections
'lots of other code
End Sub
could someone point me in the right direction to run the SQL and assign the result to the the variables. I've been reading about ExecuteScalar() and SqlDataReader but that doesn't seem to be the correct option as the only examples I've found handle a single result or lots of rows with a single column
Thanks for any samples and pointers.

Try this:
Dim da As New OleDb.OleDbDataAdapter(sql1, conn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count < 0 Then
col1h = dt.Rows(0).Item("col1h")
col2r = dt.Rows(0).Item("col2r")
col3title = dt.Rows(0).Item("col3title")
col4UQN = dt.Rows(0).Item("col4UQN")
Else
'No rows found
End If

Related

How can I compare a text box entry against a list of database values in the Text_Changed event

as the title states I am trying to compare or validate a text box entry against a list of acceptable values stored in my database. As of now I have taken the values from my database and store them in a List(of String) and I have a for loop that loops through that list and returns true if the values match, if the values do not match it will return false. Below I have attached the code I am currently working with.
Protected Sub txtSearchOC_TextChanged(sender As Object, e As EventArgs) Handles txtSearchOC.TextChanged
Dim listEType As List(Of String) = New List(Of String)
Dim eType As String = txtSearchOC.Text
Dim strResult As String = ""
lblPrefix.Text = ""
lblList.Text = ""
Dim TypeIDQuery As String = "
SELECT a.OrderCode
FROM SKU AS a
INNER JOIN EnrollmentType AS e ON a.EnrollmentTypeID = e.TypeID
INNER JOIN Enrollment AS f ON e.RecID = f.EnrollmentTypeID
WHERE f.AccountNumber = '12345';
"
Using connEType As New SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ToString)
Using cmdEType As New SqlCommand(TypeIDQuery, connEType)
cmdEType.Parameters.Add("#AccountNumber", SqlDbType.VarChar, 15).Value = "12345"
connEType.Open()
Using sdrEType As SqlDataReader = cmdEType.ExecuteReader
While sdrEType.Read
listEType.Add(sdrEType("OrderCode").ToString)
End While
End Using
End Using
End Using
For Each Item As String In listEType
strResult &= Item & ", "
Next
For i = 0 To listEType.Count - 1
If eType = listEType(i) Then
lblPrefix.Text = "True"
End If
If eType <> listEType(i) Then
lblList.Text = "Error"
End If
Next
'lblList.Text = strResult
End Sub
In the code I declare my list and a variable to store the text value of the text box. To verify that it pulled the appropriate values from the database I have the strResult variable and can confirm that the appropriate values are being stored.
The problem I am having has to do with the For loop I have at the bottom, when I enter in a valid value that is contained in the listEType, I get the confirmation message of "True" indicating it has matched with one of the values, but I also get the "Error" message indicating that it does not match. If I enter in a value that is not contained in the list I only get the "Error" message which is supposed to happen.
My question is, based on the code I have supplied, why would that For loop be returning both "True" and "Error" at the same time for a valid entry? Also, if there is a better way to accomplish what I am trying to do, I am all ears so to speak as I am relatively new to programming.
Well, as others suggested, a drop down (combo box) would be better.
However, lets assume for some reason you don't want a combo box.
I would not loop the data. You have this amazing database engine, and it can do all the work - and no need to loop the data for such a operation. Why not query the database, and check for the value?
Say like this:
Protected Sub txtSearchOC_TextChanged(sender As Object, e As EventArgs) Handles txtSearchOC.TextChanged
If txtSearchOC.Text <> "" Then
Dim TypeIDQuery As String = "
SELECT a.OrderCode FROM SKU AS a
INNER JOIN EnrollmentType AS e ON a.EnrollmentTypeID = e.TypeID
INNER JOIN Enrollment AS f ON e.RecID = f.EnrollmentTypeID
WHERE f.AccountNumber = #AccoutNumber;"
Using connEType As New SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ToString)
Using cmdEType As New SqlCommand(TypeIDQuery, connEType)
cmdEType.Parameters.Add("#AccountNumber", SqlDbType.NVarChar).Value = txtSearchOC.Text
connEType.Open()
Dim rstData As New DataTable
rstData.Load(cmdEType.ExecuteReader)
If rstData.Rows.Count > 0 Then
' we have a valid match
lblPrefix.Text = "True"
Else
' we do not have a valid match
lblPrefix.Text = "False"
End If
End Using
End Using
End If
End Sub
So, pull the data into a data table. You can then check the row count, or even pull other values out of that one row. But, I don't see any need for some loop here.

'Initializing data table before use'

how can i solve this please ?
i am doing a simple database project and i have a search field i wrote the following code for searching and displaying data in DataGridView but the
Null Reference Exception keeps showing up because i'm initializing the table with nothing and yet if i don't do so i get 'Used Before Initializing warning.
the question is :how can i initialize the table properly .
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Dim searchText As String = txtSearch.Text
Dim matchText As String = ""
Dim rowMatch As Boolean = False
Dim foundRows As DataTable = Nothing 'this initializig causes the problem of null exception,But how can i Initialize it then?????
For Each rw As DataRow In dataSet.Tables(0).Rows
Dim cl As String = rw.Item(1).ToString ' this cell is FirstName Cell
If searchText.Length > cl.ToString.Length Then
matchText = cl.ToString
Else
matchText = cl.ToString.Substring(0, searchText.Length)
End If
'bellow it adds the Found Row (rw) to the table
If (searchText.Equals(matchText) And searchText <> "" And Not foundRows Is Nothing) Then foundRows.Rows.Add(rw)
Next
'to shows data if the search text field is not empty then show the found matching rows
If (searchText <> "") Then
contactView.DataSource = foundRows
Else ' else show the original tavle again
contactView.DataSource = dataSet.Tables(0)
End If
contactView.Refresh() 'refresh
End Sub
here is the screenshot of the form
i tried to use
Dim foundRows As DataTable = New DataTable
but it shows ArgumentException
This Row already belongs to another Table
i also tried this
but as you can see nothing works please Help !
Yes
i finally got it
i was having a problem in columns
Dim foundRows As DataTable = New DataTable("PseuContact") 'this initializig causes the problem of null exception,But how can i Initialize it then?????
foundRows.Columns.Add("ID")
foundRows.Columns.Add("First Name")
foundRows.Columns.Add("Last Name")
foundRows.Columns.Add("Phone Number")
foundRows.Columns.Add("Mobile Number")
foundRows.Columns.Add("Email Address")
initializing columns is important when declaring new table
this's been the best

cannot convert string to date

Hello stack overflow residents! this is my first post and i'm hoping to receive some help.
I've searched but because I'm still very new, i was not able to full find/understand my answer.
I keep encountering this error:
Message: Conversion from string "" to type 'Date' is not valid. File:
~/reports/pendingshipments.aspx Function: btnExportXls_Click Stack
Trace: at
Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String
Value) at reports_default.btnExportXls_Click(Object sender, EventArgs
e) in C:\Users\jet.jones\Documents\ERIRoot\ERITitan\ERITitan.ssa\Web
Application\reports\pendingshipments.aspx.vb:line 75
Here is my code:
on App_code
**Public Function Reports_PendingShipments(ByVal intClientID As Integer, ByVal strMinDate As Date?, ByVal strMaxDate As Date?, ByVal xmlSiteID As String) As DataTable
'=================================================================================
' Author: Jet Jones
' Create date: 2013.05.28
' Description: Returns a data table with pending shipments for the sites specified
'=================================================================================
Dim objConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("Titan").ToString)
Dim cmdGet As New SqlCommand("spReports_PendingShipments", objConn)
Dim parClientID As New SqlParameter("#ClientID", SqlDbType.Int)
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
Dim parSiteID As New SqlParameter("#Sites", SqlDbType.Xml)
Dim objAdapter As New SqlDataAdapter(cmdGet)
Dim objTable As New DataTable
parClientID.Value = intClientID
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
parSiteID.Value = xmlSiteID
'set up the command object
cmdGet.Connection = objConn
cmdGet.CommandType = CommandType.StoredProcedure
'add the parameters
cmdGet.Parameters.Add(parClientID)
cmdGet.Parameters.Add(parMinDate)
cmdGet.Parameters.Add(parMaxDate)
cmdGet.Parameters.Add(parSiteID)
'open the connection
objConn.Open()
'execute the query and fill the data table
objAdapter.Fill(objTable)
'return the data table
Reports_PendingShipments = objTable
'clean up
objConn.Close()
objConn = Nothing
End Function**
my aspx.vb page calls this function this way (Get the values from the query):
objTable = Reports_PendingShipments(ucClientSearch.Value,
txtMinDate.Text, txtMaxDate.Text, strSites)
I'm passing the variable strSites because the website permissions allow for users to have access to one or more site locations, and if a report is run and the user selects "All Sites" from the dropdown, I only want to send the sites they have permissions to via XML.
If I'm missing any information please let me know!
anyone's prompt response is so greatly appreciated.
The problem is that your code is expecting empty dates to be NULL, it doesn't check for empty strings. You need something like this:
if len(strMinDate)=0 then
strMinDate = "01/01/1980"
end
Not sure what you want to default the minimum date to, but you need to add code similar to the IF statement above
Be sure to add this code prior to using the variable a few lines later...
First of all, you adding MaxDate parameter twice:
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
And moreover, then you setting parameters values wuthout check for HasValue:
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
Remove these lines and fix min date parameter name

Reducing SQL connections to just 1 - ASP.net VB

I am currently working on an asp.net web page with a GridView displaying a table from a database. This GridView has 4 DropDownLists that will be used to filter the data shown on the GridView. When the page loads 4 Sub routines are run, each one connecting to the database with a select statement to fill the DropDownList with relevant filter headings.
Initially, I had one connection with a loop that populated all of the drop downs but these contained duplicates. I then split the filling of each DDL so that the select statements could contain DISTINCT.
I would like (and am sure there is a way here) to be able to populate all of the DDLs with data from one connection.
Code for one connection:
Protected Sub FillDepDDL()
Dim conn As New SqlConnection()
conn.ConnectionString = WebConfigurationManager.ConnectionStrings("TestDBConnectionString").ConnectionString
Dim connection As New SqlConnection(conn.ConnectionString)
connection.Open()
Const FillAllQS As String = "SELECT DISTINCT [Department] FROM [Employees]"
Dim command As New SqlCommand(FillAllQS, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim sel As New ListItem
sel.Text = "Please Select"
sel.Value = "*"
DDLDepartment.Items.Add(sel)
While reader.Read
Dim Deplist As New ListItem()
Deplist.Value = reader("Department")
Deplist.Text = reader("Department")
DDLDepartment.Items.Add(Deplist)
End While
reader.Close()
conn.Close()
End Sub
The other 3 column names: FirstName > DDLFN, LastName > DDLLN, Wage > DDLWag.
This is only a test DB and the princibles learned here will be applied to a larger live project.
I'm sure some guru will be able to work this out easily but I just can't get my head round it even after hours of searching.
Thanks in advance.
I'm adding this in as answer because I cannot format it in a comment, but this doesn't answer the original question of how to write the sql to return all three distinct result sets. Instead, it answers how to rewrite the code you have above so that connections are properly disposed of in case of an exception.
Protected Sub FillDepDDL()
Dim Deplist As ListItem
Dim sel As New ListItem
sel.Text = "Please Select"
sel.Value = "*"
DDLDepartment.Items.Add(sel)
Using conn As New SqlConnection(WebConfigurationManager.ConnecitonString("TestDBConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT DISTINCT [Department] FROM [Employees]", conn)
conn.Open()
Using reader = cmd.ExecuteReader()
While reader.Read
Deplist = New ListItem()
Deplist.Value = reader("Department")
Deplist.Text = reader("Department")
DDLDepartment.Items.Add(Deplist)
End While
End Using
End Using
End Using
End Sub
I don't see any reason for you to try to return all three results in a single query. That will just make your code unnecessarily complicated just to save a millisecond or two. Connection pooling handles the creation of connections on the database server for you, so opening a new connection in your code is very fast.

how to maintain connection with excel with rapidly data fetching

i am making a website for trading, with trading feeds coming from a source in an excel sheet. I have to show data from the excel sheet in a gridview. When i make connection it will fail due to rapidly changing data; each cell in the sheet changes value 1-3 times per second. I am using an Ajax Timer of interval 100. Here is my code:
Public Function RetrieveExcelData(ByVal excelSheetName As String, ByVal sheetNumber As Integer) As DataSet
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
' Connection String.
Dim connString As [String] = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\Vishal\Desktop\TESTING COLOURfor web1.xls;Extended Properties=Excel 8.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
Dim i As Integer = 0
' Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
excelSheets(i) = row("TABLE_NAME").ToString()
i += 1
If i = sheetNumber Then
Exit For
End If
Next
Dim excelCommand As New OleDbCommand("Select * from [" + excelSheets(sheetNumber - 1) & "]", objConn)
Dim excelAdapter As New OleDbDataAdapter(excelCommand)
Dim excelDataSet As New DataSet()
excelAdapter.Fill(excelDataSet)
Return excelDataSet
Catch ex As OleDbException
Throw ex
Catch ex As Exception
Throw ex
Finally
' Clean up.
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try
End Function
To be honest - I cannot see how it can work. You are trying to use Excel spreadsheet as a database to store and retrieve data in real-time, for which Excel was never intended or designed.
You have mentioned that the Excel gets data several times per second. What is the source of data? RTD component? Bloomberg API? I would try to avoid the middle step of storing data in a spreadsheet.

Resources