0

I'm a little desperate, hence why I'm here! I'm quite new to programming and have been given an assignment where I need to use a range of SQL queries to generate a simple HTML report table. There is also a user input, with them selecting the ClinicID from the comboBox and clicking a button to generate the report.

Basically, I have a comboBox that I have populated with 'ClinicID', as below. I have also made sure that SelectedIndex is working. I need to somehow use this in the SQL query method which I have also provided below.

Public Class frmReport1
'Set lsData for Clinics table
Dim lsData As List(Of Hashtable)


'On form load
Private Sub frmReport1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    cboClinicID.DropDownStyle = ComboBoxStyle.DropDownList

    'Instantiate new ClinicController object
    Dim cController As ClinicController = New ClinicController

    'Load ClinicID
    lsData = cController.findId()

    For Each clinic In lsData
        cboClinicID.Items.Add(CStr(clinic("ClinicID")))
    Next

End Sub

'Selected Index 
Private Sub cboClinicID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboClinicID.SelectedIndexChanged
    Dim selectedIndex As Integer = cboClinicID.SelectedIndex
    Dim selectedItem As Object = cboClinicID.SelectedItem

    'Print in debug window
    Debug.Print("Selected clinicID: " & selectedItem.ToString())
    Debug.Print("Selected clinicID index: " & selectedIndex.ToString())

    Dim htData = lsData.Item(selectedIndex)


End Sub

SQL query method - **note, I'm pulling from two different tables:

Where the '?' is, is where I assume I have to work in the 'SelectedItem' but I have no idea how!

Desired result: an html table outputted with these three selected fields.

Public Class ClinicOrderController

Public Const CONNECTION_STRING As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=PharmDB.accdb"

'Dim cController As ClinicController = New ClinicController
'Dim oController As OrderController = New OrderController

Public Function findClinicOrder() As List(Of Hashtable)

    'Instantiates a connection object
    Dim oConnection As OleDbConnection = New OleDbConnection(CONNECTION_STRING)
    'Instantiates a list of hashtables
    Dim lsData As New List(Of Hashtable)

    Try
        Debug.Print("Connection string: " & oConnection.ConnectionString)

        oConnection.Open()
        Dim oCommand As OleDbCommand = New OleDbCommand
        oCommand.Connection = oConnection

        'Stored in the CommandText property of the command object
        'SELECT SQL statement
        oCommand.CommandText = "SELECT clinics.clinic_id, orders.date_ordered, orders.total_price FROM clinics, orders WHERE clinics.clinic_id = orders.clinic_id AND clinics.clinic_id = ? ORDER BY clinics.clinic_id"

        'Compiles the prepared statement
        'oCommand.Prepare()
        'Executes the SQL statement and stores the results in data reader object
        Dim oDataReader = oCommand.ExecuteReader()

        'Process data set in Hashtable
        Dim htTempData As Hashtable
        Do While oDataReader.Read() = True
            htTempData = New Hashtable
            htTempData("ClinicID") = CStr(oDataReader("clinic_id"))
            htTempData("DateOrdered") = CStr(oDataReader("date_ordered"))
            htTempData("OrderTotalPrice") = CStr(oDataReader("total_price"))
            lsData.Add(htTempData)

        Loop

        Debug.Print("The record was found.")

    Catch ex As Exception
        Debug.Print("ERROR:" & ex.Message)
        MsgBox("An error occured!")
    Finally
        oConnection.Close()
    End Try

    'Return list of hashtables to the calling function
    Return lsData

End Function

Really, really appreciate any help here. Ive been struggling with this for more than 8 hours (not joking - I give you permission to laugh)

antisonfire
  • 11
  • 1
  • 4
  • @Japz Divino Appreciate the response. Sadly I get an exception error for this code (this helps generate the HTML table) -the error is for the HtSample line. `code`Private Function generateTable(ByVal lsData As List(Of Hashtable)) As String ' Generate the start of the table     Dim sTable = "" & vbCrLf Dim htSample As Hashtable = lsData.Item(0) Dim lsKeys As List(Of String) = New List(Of String) lsKeys.Add("ClinicID") lsKeys.Add("DateOrdered") lsKeys.Add("OrderTotalPrice") `code`
    – antisonfire Sep 30 '15 at 08:16
  • This is not what SO is about (i.e., asking about specific problems which might be helpful for future readers). For analysing a code, you should go to Code Review (http://codereview.stackexchange.com/). In any case, being unclear and expecting people to waste their time to understand and fix your problems does not seem the best proceeding to get help. – varocarbas Sep 30 '15 at 08:33
  • This post belongs to Code Review. – varocarbas Sep 30 '15 at 08:37
  • 1
    @varocarbas This would be off topic on Code Review. CR isn't for changing what the code does, it's about giving feedback on already working code. – SuperBiasedMan Sep 30 '15 at 08:40
  • 1
    @SuperBiasedMan Thanks for the clarification. Then, this post is off-topic everywhere. – varocarbas Sep 30 '15 at 08:47
  • Thanks for the response @varocarbas. I am new here, so welcome any responses. Where would I post a question like this where I'm *adding* to a code to try and implement more functionality? – antisonfire Sep 30 '15 at 09:05
  • When you have a problem with a code or with an implementation, you should perform a step-by-step analysis and locate the problematic parts. Once you have done that you should try to fix them/come up with an alternative approach, by mostly relying on your own expertise. If there are specific issues which you are not too sure about, you might look for some assumed-to-be-right references (e.g., a manual, MSDN or even SO posts). If after this whole process you realise that you need some advice from a more experienced person to put all your ideas together, you might ask in SO... – varocarbas Sep 30 '15 at 09:12
  • @varocarbas Ah, that's fair. I do realise this just looks like a big dump of code. I've only been programming in VB (and at all) for about 8 weeks, so it's tough for me to narrow things down as I properly should. I know what the problem is (i.e. what functionality I need) and I know the general structure, but it's hard for me to know exactly what is causing the problem. With something like this where my lecturer wants it done a specific way that perhaps is a little strange, it seems very difficult to find material on that I can self-study (I've tried, believe me! This was my last resort). – antisonfire Sep 30 '15 at 09:15
  • ... That is: SO is not for solving your problems for you. It is just another source you can use to help you perform your work (or even learning). You have to bear in mind that people provide help in SO generously because of wanting to somehow contribute towards building a reliable source of programming knowledge. If you come here with your egoist needs, you don't make any effort by your own to solve the given problem (not even to explain your situation), your request would most likely be considered off-topic (or people would plainly ignore you). You should take a look at the help pages. – varocarbas Sep 30 '15 at 09:17
  • Note that this is not a site to learn programming; but a site for programmers. You should take care of the learning by your own (and eventually use SO for specific issues, as a complement of your learning process; as said: as a book or any other online reference). – varocarbas Sep 30 '15 at 09:18
  • I feel like you're being overly harsh here; but that's fine, I will try elsewhere. I felt like I did try and explain my problem and it is a problem that could be bothering someone else. Do you really believe that no one else has tried to use 'SelectedItem' in a SELECT query and had trouble linking the two? 'Egoist'? Wow. Way to make a new user feel welcome. Thanks to @SuperBiasedMan for trying to talk about the problem posted, rather than launch a personal attack on someone they don't know. If anyone is flexing their ego here, it's you. – antisonfire Sep 30 '15 at 09:32
  • so basically you have the clinic id and sql command, but don't know how to put the clinic id into the sql command? – codersl Sep 30 '15 at 12:58
  • @coders exactly - and I'm using a comboBox to populate clinic id, then SelectedIndex/SelectedItem to 'register' the value as being selected. The results of that SQL command are then used to generate a HTML report. – antisonfire Sep 30 '15 at 22:23

3 Answers3

0

If i understand you correctly, you want to use your dropdown selected item in your WHERE clause. To achieve that , revise your joining using INNER JOIN with ON then place your filtering in WHERE condition. Hope code below will help.

    SELECT clinics.clinic_id,
      , orders.date_ordered
      , orders.total_price 
    FROM clinics INNER JOIN orders ON clinics.clinic_id = orders.clinic_id
    WHERE clinics.clinic_id = selectedItem.ToString()
    ORDER BY clinics.clinic_id

if the selectedItem.ToString() did not work, you can try SelectedValue

japzdivino
  • 1,736
  • 3
  • 17
  • 25
  • Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. It's also recommended that you don't post an answer if it's just a guess. A good answer will have a plausible reason for why it could solve the OP's issue. – SuperBiasedMan Sep 30 '15 at 08:39
  • Hey, this solution makes sense to me and is what I was trying earlier - but I'm not sure how to get the SELECT statement to actually use the selectedItem value. Doing it this way doesn't seem to work. Appreciate the response, though. – antisonfire Sep 30 '15 at 09:06
  • @SuperBiasedMan post modified.. my answer is based on my understanding to the question NOT a guess. – japzdivino Sep 30 '15 at 09:07
0

Assuming that clinic_id is a numeric field in the database: (otherwise just surround it with single quotes (''))

string clinicID = cboClinicID.SelectedItem.ToString();
string sql = string.Format(@"SELECT clinics.clinic_id, orders.date_ordered, orders.total_price
                             FROM clinics, orders
                             WHERE clinics.clinic_id = orders.clinic_id
                             AND clinics.clinic_id = {0}
                             ORDER BY clinics.clinic_id", clinicID);

oCommand.CommandText = sql;

You can also do it like this:

string sql = "SELECT clinics.clinic_id, orders.date_ordered, orders.total_price " +
             "FROM clinics, orders " +
             "WHERE clinics.clinic_id = orders.clinic_id " +
             "AND clinics.clinic_id = " + clinicID + " " +
             "ORDER BY clinics.clinic_id";
codersl
  • 2,222
  • 4
  • 30
  • 33
-1

Please provide code in vb.net

Here is my code, I want to display prize amount from table where class id is condition :

If class id is 3 then prize for that is display in my textbox named txtprize.text and class Id is displayed in list box.

Private Sub listClassID_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listClassID.SelectedIndexChanged
Dim classIdlist As String
classIdlist = New String(listClassID.SelectedItem.ToString)
Dim strSQL As String = "select [Prize Amount] from Master_Class WHERE [Class ID]  =" & classIdlist
Dim dr As SqlDataReader

Try
    con.Open()
    cmd = New SqlCommand(strSQL, con)
    dr = cmd.ExecuteReader()
    If dr.Item(0) Then
        txtPrize.Text = dr("[Prize Amount]").ToString
    End If

    dr.Close()
    cmd.Dispose()
    con.Close()

Catch ex As Exception
    MsgBox(ex.Message)
    con.Close()
End Try
End Sub
tobi6
  • 8,033
  • 6
  • 26
  • 41