I have around 14 pages with 6-10 questions on each which are all
true and false answers, Written to the DB as 1 and 0.
I have created
a summary page so it is printable which contains all 14 pages with all 6-10
questions on each then I want to display the answer by the question via a
Label
I am very bad at VB.net and SQL so any help on this would be
great
I managed to get the first one working, to display as "Yes or No"
but the second one doesn't work
Is anyone able to
formulate a function so I can just call a single line of code for each label
instead of having a ton of if statements?
I'm super bad at sql and vb
and have hardly any experience so any help will be appreciated.
This is
the code I currently have, Please edit as needed (if its even right?)
Imports System.Data
Imports System.Data.SqlClient
Public Class DraftPrint
Inherits System.Web.UI.Page
Dim con As New SqlConnection
Dim comm_Id As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
comm_Id = Request.QueryString("Comm").ToString
con.ConnectionString = "Data Source=YK15-YKC0201;Initial Catalog=Testing;Integrated Security=true"
con.Open()
Dim cmd As New SqlCommand
cmd.Connection = con
Dim str As String = "Select Indicator, Question, Answer From maca where community_ID =" + comm_Id.ToString + " order by Indicator ASC"
Dim adapter As SqlDataAdapter = New SqlDataAdapter(str, con)
Dim dt_summary As DataTable = New DataTable
adapter.Fill(dt_summary)
Dim indicator As Integer = dt_summary.Rows(0)(0)
Dim question As Integer = dt_summary.Rows(0)(1)
Dim answer As String = dt_summary.Rows(0)(2)
If question = 1 And answer = False Then
DraftPrint1.Text = "No"
Else
DraftPrint1.Text = "Yep"
End If
If indicator = 1 And question = 2 And answer = False Then
DraftPrint2.Text = "No"
Else
DraftPrint2.Text = "Yep"
End If
This is just one of the ways to solve it. You can prepare everything in the query as:
Select Indicator, Question,
CASE
WHEN Answer = 1 And Indicator = 1 THEN "Yes" /* Not sure what indicator is but lets pretend it must be 1 for success */
ELSE "No"
END as Answer
FROM
...
Now, one of the way to map it in code is to Order By Question (assuming question number)
DraftPrint1.Text = dt.rows(1-1)("Answer").ToString()
DraftPrint2.Text = dt.rows(2-1)("Answer").ToString()
......
As you see, this way everything comes from DB ready to populate your label, so all you have to do is to map right row to right label. To avoid confusion I use (1-1) technique. You could also do dynamic control creation based on your query resultset - this way you wouldn't need to know numbers of your controls upfront.
Related
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
I have a few more questions regarding my latest project. Ive felt like I have made some pretty good strides over the last couple days, but I am still struggling on a few of the core concepts of the SQL libraries, namely reading from specific columns and deleting entire rows.
Over the last week I was able to build a webform, save excel files to the server, open those files and export data into specific SQL tables, and bind the data to specific data grids depending on what the user chooses through a dropdown.
What I would like to accomplish is: Dynamic population of another dropdown depending on what the user chooses from the first drop down. More specifically, I have 4 tables, in the first column of each table I have serial numbers, if the user chooses Table2 in the first drop down, I would like the second dropdown to display all the serial numbers from column1 of Table2. Then if the user choose a specific serial number from the second drown down it populates a datagrid with columns 1-5 of that related row.
The second part is to create a delete button that the user can push after the information is displayed in the datagrid, that deletes the entire row of the serial number entry from that table.
This is what I have managed to Frankenstein together from other examples:
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As System.EventArgs)
DropDownList2.Enabled = True 'its remains disabled until the user selects something from the first box
Using con As New SqlClient.SqlConnection
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=" & AppPath & "App_Data\DeviceDatabase.MDF;Integrated Security=True;User Instance=True;"
Using cmd As New SqlClient.SqlCommand
cmd.Connection = con
End Using
Dim cmdSQL As New SqlCommand()
cmdSQL.CommandType = Data.CommandType.Text
cmdSQL.CommandText = "SELECT Fieldname1 FROM " & """" & DropDownList1.SelectedItem.ToString & """" 'Im pretty sure this isnt right, and the reason I use """"" is because some of the items in the dropdown have spaced words.
Dim adptSQL As New SqlClient.SqlDataAdapter(cmdSQL)
Dim myDataSet As New DataSet()
adptSQL.Fill(myDataSet)
With myDataSet.Tables(DropDownList1.SelectedIndex) 'I think this is right
For rowNumber As Integer = 0 To .Rows.Count - 1
With .Rows(rowNumber)
DropDownList2.Items.Add(col1.rowNumber) 'This is obviously not working
End With
Next
End With
End Using
End Sub
Then, Im not quite sure how to populate the data table with the row that was selected, though currently I am able to do the entire table with using:
Private Sub GenTables(ByVal DropList As Object)
If DropList.SelectedIndex = 0 Then
GridView1.DataSourceID = Nothing
ElseIf DropList.SelectedIndex = 1 Then
GridView1.DataSourceID = "SqlDataSource1"
ElseIf DropList.SelectedIndex = 2 Then
GridView1.DataSourceID = "SqlDataSource2"
ElseIf DropList.SelectedIndex = 3 Then
GridView1.DataSourceID = "SqlDataSource3"
ElseIf DropList.SelectedIndex = 4 Then
GridView1.DataSourceID = "SqlDataSource4"
End If
GridView1.DataBind()
End Sub
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DeviceDatabaseConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:DeviceDatabaseConnectionString1.ProviderName %>"
SelectCommand="SELECT [Device:] AS column1, [SWversion:] AS column2, [Date:] AS column3, [Tester:] AS column4, [Wifi Preferred InCov:] AS column5 FROM [Galaxy Nexus]">
</asp:SqlDataSource>
'there are 3 more of these.
But I have these tables "hard coded" into the application, I can't obviously do this with every single table row. So how do I populate a datagrid without setting a SQLDataSource ahead of time in asp?
And lastly deleting the row that relates to the information displayed in the datagrid on the click of a button. If if can get a little help with the first part, Im sure I can figure out the second part.
So pretty much what I am asking is: how to populate a drop down with all the items from Coloumn1? and how to populate a datagrid from a specific row?
Any and all help is always greatly appreciated. Thanks Guys
Zach
EDIT
hmm I think I was making this a ton harder then it had to be, right now I am working with this:
Protected Sub BindDrop_Click(sender As Object, e As System.EventArgs)
DropDownList2.DataSourceID = "SqlDataSource5"
DropDownList2.DataBind()
End Sub
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:DeviceDatabaseConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:DeviceDatabaseConnectionString1.ProviderName %>"
SelectCommand="SELECT [Device:] AS column1 FROM [Galaxy Nexus]">
Its not quite right but its closer and in 1/10th the lines
alright guys i figured it out, I needed to use the ExecuteReader function (which crazily enough I couldnt find one article in auto population that uses this method). Hopefully in writing/answering this I make someone's life much easier.
Protected Sub DropDownList2_SelectedIndexChanged(sender As Object, e As System.EventArgs)
DropDownList3.Enabled = True
DropDownList3.Items.Clear()
Dim newsqlcommand As String = "Select [SWversion:] FROM " & """" & DropDownList2.SelectedItem.ToString & """"
Using con As New System.Data.SqlClient.SqlConnection(connexstring)
con.Open()
Using cmd As New SqlCommand(newsqlcommand, con)
Dim myReader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While myReader.Read()
DropDownList3.Items.Add(myReader.GetString(0))
End While
myReader.Close()
cmd.Dispose()
End Using
con.Close()
con.Dispose()
End Using
Dbind()
End Sub
This successfully reads all the items in the column "SWVersion" and adds them to the dropdown in dropdown3. Enjoy!
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.
I used to use datasets instead of sqldatareaders and I used to be able to do something like this
If dataset.tables(0).Rows(0)(1).ToString()) = "N" Then
lbl.Text = dataset.tables(0).Rows(0)(2).ToString())
Else
'Do Nothing
End If
This obviously doesn't work with sqldatareaders.
I have code to see if the SQLDatareader has any rows but was wondering if there was a way to get the value of each row
I'm guessing this is possible and i've had a look around but can't seem to find anything
Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'")
conn.Open()
Dim query As New SqlCommand("DECLARE #investor varchar(10), #sql varchar(1000) Select #investor = 69836 select #sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + #investor + ''''''')' EXEC(#sql)", conn)
Dim oDR As SqlDataReader = query.ExecuteReader()
If oDR.HasRows or dataset.tables(0).Rows(0)(1).ToString()) = "N" Then
lbl.Text = dataset.tables(0).Rows(0)(2).ToString())
Else
'Do Nothing
End If
That is the code I have at the moment which obviously doesn't work
Any ideas?
Thanks
When you use the data reader you have to step through each row yourself. Using HasRows is a good start, for it will tell you if the returned result set is empty.
To iterate through the result set you should use the Read() method. It will return true if you are at a row and false when you have moved past the last row.
My Vb is poor so I will give you an example in C# instead:
if (oDR.HasRows && oDR.Read())
{
if (oDR.GetString(0) == "N")
{
lbl.Text = oDr.GetString(1);
}
}
Here I first check that we have a result set with data and then try to move to the first row. If this succeeds I then read the string value of the first column and compare it to "N". If the value is equal to "N" I set the Text property of the lbl variable to the string value of the second column.
This should be equivalent to your algorithm with the dataset. I recommend that you read the MSDN documentation for the SqlDataReader. It is quite good and the example code is useful.
I have a page with 3 dropdownlist, 2nd and 3rd dropdownlist are added with CascadingDropDown. 3rd dropdownlist will take parameters from 1st and 2nd dropdownlist. So, in current example for CascadingDropDown i have found from google, they are only passing one parameter to the WebService method. How can pass two parameters to the service method, so that my 3rd dropdownlist will based on the SelectedValue of 1st and 2nd dropdownlist?
<WebMethod()> _
Public Function GetTeams(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim strConnection As String = ConfigurationManager.ConnectionStrings("nerdlinessConnection").ConnectionString
Dim sqlConn As SqlConnection = New SqlConnection(strConnection)
Dim strTeamQuery As String = "SELECT * FROM TEAM WHERE conf_id = #confid"
Dim cmdFetchTeam As SqlCommand = New SqlCommand(strTeamQuery, sqlConn)
Dim dtrTeam As SqlDataReader
Dim kvTeam As StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Dim intConfId As Integer
If Not kvTeam.ContainsKey("Conference") Or Not Int32.TryParse(kvTeam("Conference"), intConfId) Then
Return Nothing
End If
cmdFetchTeam.Parameters.AddWithValue("#confid", intConfId)
Dim myTeams As New List(Of CascadingDropDownNameValue)
sqlConn.Open()
dtrTeam = cmdFetchTeam.ExecuteReader
While dtrTeam.Read()
Dim strTeamName As String = dtrTeam("team_name").ToString
Dim strTeamId As String = dtrTeam("team_id").ToString
myTeams.Add(New CascadingDropDownNameValue(strTeamName, strTeamId))
End While
Return myTeams.ToArray
End Function
This is the sample code i found! As you can see in the code, '#confid' will be passed from 2nd dropdownlist! So, hw do i modify this code to get the selected value from 1st dropdownlist as well??
Which web service are you referring to? Is it something you have written or someone else's webservice?
In case it is your webservice, update the method definition in it and pass two parameters. In case it is somone else's, contact the concerned person to know what best can be done.
It appears the poster is not asking about Web Services really, but about SqlCommand and adding parameters.
First, you should never EVER run sql straight from your web application like that. Put it in a stored procedure.
Second, you should run checks on the values coming in, because this is a good way for your web site users to use SQL injection attacks.
Now... Here is what you were looking for:
Dim strTeamQuery As String = "SELECT * FROM TEAM WHERE conf_id = #confid"
becomes
Dim strTeamQuery As String = "SELECT * FROM TEAM WHERE conf_id = #confid AND second_id = #secondId"
Then just add another one of these:
cmdFetchTeam.Parameters.AddWithValue("#confid", intConfId)
(with the other value, of course, like this)
cmdFetchTeam.Parameters.AddWithValue("#confid", intConfId)
cmdFetchTeam.Parameters.AddWithValue("#secondId", intSecondId)