-3

I have a Vb.net program that queries a database to get a bunch of records. I can't quite figure out how to pass parameters. below is my code:

Dim connectionString As String
    Dim sqlCnn As SqlConnection
    Dim sqlCmd As SqlCommand
    Dim sql As String

    Private Function GetCustomerData() As DataTable
        locationdb = "10.0.1.1"

        connectionString = ("Data Source=" & locationdb & ";Initial     Catalog=TestDB;Persist Security Info=True;User ID=user;Password=password")
        sql = ("SELECT lCustomerID,CustomerName,address FROM customers where @active = True...ETC")
        sqlCnn = New SqlConnection(connectionString)
        Dim CategoryAdapter As New SqlDataAdapter(sql, sqlCnn)
        Dim CustomerInfo As New DataSet()
        sqlCmd.Parameters.AddWithValue("@StartDate", frmMain.Startdate)
        sqlCmd.Parameters.AddWithValue("@EndDate", frmMain.Enddate)
        sqlCmd.Parameters.AddWithValue("@Department", "ALL")
        sqlCmd.Parameters.AddWithValue("@Active", "1")
        sqlCmd.Parameters.AddWithValue("@Visits", "ALL")
        CategoryAdapter.Fill(CustomerInfo, "Customers")
        Return CustomerInfo.Tables(0)
    End Function

I need to pass:

@stardate
@enddate
@Deparment
@Active
@Visits

I am receiving the error:

   NullReferenceException was unhandled.  Object reference not set to an instance of an    object.

at line:

  sqlCmd.Parameters.AddWithValue("@StartDate", frmMain.Startdate)

frmMain.Startdate and frmMain.Enddate are defined by a Datetime picker datetimepicker1 and datetimepicker2 on frmMain

Shmewnix
  • 1,553
  • 10
  • 32
  • 66
  • have you completed or executed a GOOGLE Search on SqlDataAdapter and Parameters.AddWithValue() Method – MethodMan Jun 03 '14 at 19:42
  • this is quite simple actually I will convert my C# method to VB and you can use that as a template / guide try to show more effort next time – MethodMan Jun 03 '14 at 19:43
  • http://msdn.microsoft.com/en-us/library/yy6y35y8(v=vs.110).aspx – Ňɏssa Pøngjǣrdenlarp Jun 03 '14 at 19:43
  • http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand%28v=vs.110%29.aspx too easy – porkchop Jun 03 '14 at 19:46
  • I'll edit my post. I have been trying all afternoon and I continue to get errors. Perhaps I should have posted where I have gotten, instead of posting my "start-over" point – Shmewnix Jun 03 '14 at 19:56
  • I tested the code example that I have posted and created as stored procedure and used your SQl and it works.. so basically for you you need to define a connection string in your config file and 2nd create a stored procedure and make sure you call the function properly and all should be well – MethodMan Jun 03 '14 at 19:59
  • I'll have a look at your example. In the meantime, I edited my question. – Shmewnix Jun 03 '14 at 20:04
  • first of all show where you define startdate and how you assign it.. – MethodMan Jun 03 '14 at 20:05
  • `CategoryAdapter.Fill(CustomerInfo, "Customers")` look at how I am creating the DataSet and then calling the fill method try to follow the working example – MethodMan Jun 03 '14 at 20:07
  • `"SELECT lCustomerID,CustomerName,address FROM customers where @active = True...ETC")` your table knows nothing about @active` this will also cause a problem once you fix the code to the working example – MethodMan Jun 03 '14 at 20:09
  • the query is 4 lines long... I just put in a basic query – Shmewnix Jun 03 '14 at 20:10
  • so you're telling me that you have a column in your database named @active..? look at that query again what is the datatype of Active Integer, Bool Bit..etc..? – MethodMan Jun 03 '14 at 20:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/55019/discussion-between-dj-kraze-and-shmewnix). – MethodMan Jun 03 '14 at 20:14

1 Answers1

7

here is an example of what you can use and how to pass Parameters you have to make the changes where necessary

Public Shared Function GetCustomerInfo(stardate As DateTime, enddate As DateTime, Department As String, Active as String, Visits as Int33) As List(Of String)
    Dim cszList = New List(Of String)()
    Dim DSCityStateZipLookup As New DataSet()
    'load the List one time to be used thru out the intire application
    Dim ConnString = System.Configuration.ConfigurationManager.ConnectionStrings("CMSConnectionString").ConnectionString
    Using connStr As New SqlConnection(ConnString)
        Using cmd As New SqlCommand("your Stored Proc name goes here", connStr)
            cmd.Parameters.AddWithValue("@stardate", stardate)//make sure you assign a value to startdate
            cmd.Parameters.AddWithValue("@enddate", enddate)//make sure you assign a value to enddate
            cmd.Parameters.AddWithValue("@Deparment", Deparment)//make sure you assign a value to //Department
            cmd.Parameters.AddWithValue("@Active", Active)//make sure you assign a value to Active
            cmd.Parameters.AddWithValue("@Visits", Visits)//make sure you assign a value to Visits
            cmd.Connection.Open()
            New SqlDataAdapter(cmd).Fill(DSCityStateZipLookup)
            'If we get a record back from the above stored procedure call, that in itself means the information the user provided from
            'the UI is in the database. On the other hand, if we do not get a record back from the stored procedure call, we should
            'simply advise the user that the information they provided does not exist in the database, and to double check their spelling.
            If DSCityStateZipLookup.Tables.Count = 0 OrElse (DSCityStateZipLookup.Tables.Count > 0 AndAlso DSCityStateZipLookup.Tables(0).Rows.Count = 0) Then
                cszList.Add("Your Error Message goes here if any.")
            End If
        End Using
    End Using
    Return cszList
End Function
MethodMan
  • 18,625
  • 6
  • 34
  • 52
  • I am not passing in SQL Injected Code I create a Stored Procedure study the code example and implement the code from the ConnString down and replace as well as add in the missing Parameters @LarsTech thanks for the edit – MethodMan Jun 03 '14 at 19:47
  • yes, for sproc, pass the sproc as the first parameter to `sqlCommand` here: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand%28v=vs.110%29.aspx or set `CommandText` property. as per the CTOR http://msdn.microsoft.com/en-us/library/877h0y3a%28v=vs.110%29.aspx – porkchop Jun 03 '14 at 19:49
  • prokchop what are you doing can you not read the code that was posted – MethodMan Jun 03 '14 at 20:03
  • 'New SqlDataAdapter(cmd).Fill(DSCityStateZipLookup)' is a Syntax error inside vb.net – Shmewnix Jun 03 '14 at 20:13
  • 4
    should be `Dim DBA = New SqlDataAdapter(cmd)...` or `Using`. or well... also, the `Using` block on `sqlCommand` is unnecessary. also opening the connection is redundant. datadapter will do that. – porkchop Jun 03 '14 at 20:34
  • better check out what using is used for and how to use it porkchop your comments are not helpful – MethodMan Jun 03 '14 at 21:14
  • it creates another try/finally block. you can just `.Close()` it manually after the connection's `End Using` statement. since you're already trapping for an exception. anyways, small matter of efficiency. all my comments are very helpful... always, tvwm :). – porkchop Jun 03 '14 at 21:36
  • actually I think that you are missing what is going on I have been working with the OP in private conversation his main issue is that he was not passing needed values to the function he needs to refactor the method to return a DataSet as well – MethodMan Jun 03 '14 at 21:41
  • @DJKRAZE that's fine. i'm not disputing anything... i'm just saying, if you read the docs, what i mentioned is true. some of it is redundant. :) no offense or anything, i'm sure OP is appreciative of the help. good luck. – porkchop Jun 03 '14 at 21:43
  • no offense taken.. I totally agree with what you are saying.. I think that it was confusing the OP that's all – MethodMan Jun 03 '14 at 21:45
  • you're welcome I am glad that you have this working :) – MethodMan Jun 05 '14 at 21:48
  • For readers of this Q&A: [AddWithValue is Evil](http://www.dbdelta.com/addwithvalue-is-evil/), [AddWithValue is evil!](http://chrisrickard.blogspot.com/2007/06/addwithvalue-is-evil.html), and [Can we stop using AddWithValue() already?](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/). Those links all contain better alternatives. – Andrew Morton Apr 06 '20 at 12:11