Results 1 to 20 of 20

Thread: [RESOLVED] System.NullReferenceException Error

  1. #1

    Thread Starter
    Member Logit's Avatar
    Join Date
    Jan 2018
    Posts
    46

    Resolved [RESOLVED] System.NullReferenceException Error

    .
    I don't understand the error. Anyone ?

    Also, why does VB .NET give correction suggestions for other errors but not this one ? Did I miss a setting during the setup procedure ?

    Thank you !


    Name:  txtFirstName.jpg
Views: 3015
Size:  16.0 KB

  2. #2

    Thread Starter
    Member Logit's Avatar
    Join Date
    Jan 2018
    Posts
    46

    Re: System.NullReferenceException Error

    .
    Ok ... I've been able to correct a few other mistakes I wasn't aware of but the error posted in #1 is still there when I try to upate a record.

    Code:
    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
            Dim da As OleDb.OleDbDataAdapter    'Holds a SQL String
            Dim cb As New OleDb.OleDbCommandBuilder(da)
            Dim ds As New DataSet           'Holds a Dataset Object
    
            ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text
            ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
    
            da.Update(ds, "AddressBook")
    
            MessageBox.Show("Data updated")
        End Sub

  3. #3
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,181

    Re: System.NullReferenceException Error

    There is lots wrong with this,
    Code:
    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
            Dim da As OleDb.OleDbDataAdapter    'Holds a SQL String
            Dim cb As New OleDb.OleDbCommandBuilder(da)
            Dim ds As New DataSet           'Holds a Dataset Object
    
            ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text
            ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
    
            da.Update(ds, "AddressBook")
    
            MessageBox.Show("Data updated")
        End Sub
    "Dim da As OleDb.OleDbDataAdapter" this creates a space in memory for the dataadapter but doesn't create it you need "Dim da As NEWS OleDb.OleDbDataAdapter"
    a dataadpter has two parameters, a SQL string and a Connection string. How haven't provided either.

    There is really no need to create a DataSet if your only using one DataTable. Datasets are for holding multiple Datatables.

    "ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text" you haven't created datatable "AddressBook", so it can't be in the dataset. Unless you have done this earlier at the form level, what is "inc", where is it created.

    Anytime you get a NullReferenceException it mean some Object is Nothing. Usually you can spot it in the line of code that throws the error.

    Well that's a start.

  4. #4
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,181

    Re: System.NullReferenceException Error

    btw - do you know about the Imports Statement. By importing a Namespace you can shorten your code.

    Code:
    Imports System.Data.OleDb
    Public Class Form1
        Private con As New OleDbConnection(My.Settings.WaterConnectionString)
        Private da As New OleDbDataAdapter("Select groupId, Crop From Groups", con)
        Private dt As New DataTable
    
        Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
            Try
                da.Fill(dt)
                Me.DataGridView1.DataSource = dt
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
    End Class

  5. #5

    Thread Starter
    Member Logit's Avatar
    Join Date
    Jan 2018
    Posts
    46

    Re: System.NullReferenceException Error

    .
    wes4dbt

    Thank you for your insight. I believe the"online instruction course" I am referencing is not what it claims to be. There is too much left out in the instruction .. either the author has overlooked things or assumes the reader knows what to do. Funny ... if you are trying to learn why would you assume the reader understands ?

    I should have included the entire code that has been created so far. Here it is below :

    Code:
    Public Class Form1
        Private inc As Integer
    
        Private Sub TblContactsBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TblContactsBindingNavigatorSaveItem.Click
            Me.Validate()
            Me.TblContactsBindingSource.EndEdit()
            Me.TableAdapterManager.UpdateAll(Me.AddressBookDataSet)
    
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'AddressBookDataSet.tblContacts' table. You can move, or remove it, as needed.
            Me.TblContactsTableAdapter.Fill(Me.AddressBookDataSet.tblContacts)
    
        End Sub
    
        Private Sub BtnLoad_Click(Sender As Object, e As EventArgs)
    
    
            Dim con As New OleDb.OleDbConnection    'The Connection Object
    
            Dim dbProvider As String        'Holds the provider
            Dim dbSource As String          'Holds the Data Source
            Dim MyDocumentsFolder As String     'Holds the Documents Folder
            Dim TheDatabase As String       'Holds the Database Name	
            Dim FullDatabasePath As String      'Holds the Database Path
            Dim ds As New DataSet           'Holds a Dataset Object
            Dim da As OleDb.OleDbDataAdapter    'Holds a SQL String
            Dim sql As String
    
            'Set up the Provider
            dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    
            'Set the databse and where the database is
            TheDatabase = "/AddressBook.mdb"
            MyDocumentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            FullDatabasePath = MyDocumentsFolder & TheDatabase
    
            'Set the datasource
            dbSource = "Data Source = " & FullDatabasePath
    
            'Set the connection string
            con.ConnectionString = dbProvider & dbSource
    
            'Open the database
            con.Open()
    
            'Store the SQL string
            sql = "Select * FROM tblContacts"
            'sql above underscored as error. 
    
            'Pass the SQL string and connection object to the Data_Adapter
            da = New OleDb.OleDbDataAdapter(sql, con)
    
            'Open the Database
            MessageBox.Show("DB Open")
    
            'Close the Database
            con.Close()
            MessageBox.Show("DB Closed")
    
            txtFirstName.Text = CType(ds.Tables("AddressBook").Rows(0).Item(1), String)
            txtSurname.Text = CType(ds.Tables("AddressBook").Rows(0).Item(2), String)
        End Sub
    
        Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
            Dim da As NEWS OleDb.OleDbDataAdapter'Holds a SQL String
            Dim cb As New OleDb.OleDbCommandBuilder(da)
            Dim ds As New DataSet           'Holds a Dataset Object
            Dim Sql As String
            Dim con As New OleDb.OleDbConnection    'The Connection Object
    
            'Pass the SQL string and connection object to the Data_Adapter
            da = New OleDb.OleDbDataAdapter(Sql, con)
    
            ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text
            ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
    
            da.Update(ds, "AddressBook")
    
            MessageBox.Show("Data updated")
        End Sub
    End Class
    And ... it seems to me that this Sub : Private Sub BtnLoad_Click(Sender As Object, e As EventArgs) is no longer required for this project? It was part of the initial instruction in the series.

  6. #6

    Thread Starter
    Member Logit's Avatar
    Join Date
    Jan 2018
    Posts
    46

    Re: System.NullReferenceException Error

    .
    Re your post #4 .. No

    I'm trying to learn with Vb .Net Community Edition 2017. Previously I've used VB5 and most recently VBA for Excel. This learning curve is huge, even with the similarities.

  7. #7
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: System.NullReferenceException Error

    vb.net Code:
    1. Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
    2.         Dim da As NEWS OleDb.OleDbDataAdapter'Holds a SQL String
    3.         Dim cb As New OleDb.OleDbCommandBuilder(da)
    4.         Dim ds As New DataSet           'Holds a Dataset Object
    5.         Dim Sql As String
    6.         Dim con As New OleDb.OleDbConnection    'The Connection Object
    7.  
    8.         'Pass the SQL string and connection object to the Data_Adapter
    9.         da = New OleDb.OleDbDataAdapter(Sql, con)
    10.  
    11.         ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text
    12.         ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
    13.  
    14.         da.Update(ds, "AddressBook")
    15.  
    16.         MessageBox.Show("Data updated")
    17.     End Sub
    wes4bt's point was that the first line of that method was declaring an OleDbDataAdapter variable but not creating an object to assign to it. It is the 'New' keyword that creates the object and you left that out. "NEWS" was a typo. The thing is, you now have a line later on in the code that creates the OleDbDataAdapter object and assigns it to that variable. You don't need to create two of them. Also, you create the adapter after you create OleDbCommandBuilder, so that's two late. you have to create the adapter so that it exists when you pass it to the command builder's constructor. Also, you pass 'Sql' to the data adapter constructor without ever assigning anything to 'Sql'.

    I suggest that you follow the CodeBank link in my signature below and check out my thread on Retrieving & Saving Data. It doesn't go into detailed explanations but it does provide examples of code patterns for common ADO.NET scenarios.

  8. #8

    Thread Starter
    Member Logit's Avatar
    Join Date
    Jan 2018
    Posts
    46

    Re: System.NullReferenceException Error

    .
    jmcilhinney :

    If you are referring to this URL : http://www.vbforums.com/showthread.p...ses&highlight=

    I skimmed over it. Looks to be informative and to the point. Love the examples. I'll take a look at it tomorrow - late here now.

    Thank you.

  9. #9
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,181

    Re: System.NullReferenceException Error

    You've got a mixed bag of things going on. Here, you're using a TableAdapter and a Typed Dataset
    Code:
        Private Sub TblContactsBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TblContactsBindingNavigatorSaveItem.Click
            Me.Validate()
            Me.TblContactsBindingSource.EndEdit()
            Me.TableAdapterManager.UpdateAll(Me.AddressBookDataSet)
    
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'AddressBookDataSet.tblContacts' table. You can move, or remove it, as needed.
            Me.TblContactsTableAdapter.Fill(Me.AddressBookDataSet.tblContacts)
    
        End Sub
    In btnLoad/btnUpdate you're using a DataAdapter and an UnTyped Dataset.

    If you've used VB5 then know about variable Scope. So the variable/objects that you create in a Sub/Function, like "Dim sql As String" can't be used except in that procedure.

    So in btnUpdate,
    Code:
        Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
            Dim da As NEWS OleDb.OleDbDataAdapter'Holds a SQL String
            Dim cb As New OleDb.OleDbCommandBuilder(da)
            Dim ds As New DataSet           'Holds a Dataset Object
            Dim Sql As String
            Dim con As New OleDb.OleDbConnection    'The Connection Object
    
            'Pass the SQL string and connection object to the Data_Adapter
            da = New OleDb.OleDbDataAdapter(Sql, con)
    
            ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text
            ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
    
            da.Update(ds, "AddressBook")
    
            MessageBox.Show("Data updated")
        End Sub
    You need to set the values for "Sql", "con" and all other variables/object used in that procedure. Except "inc" because it was declared at the Form level and be seen by any procedure in the Form.

    edit - as I said before, you don't need a Dataset for one Datatable, it serves no purpose. But if your going to use one then you have to add the DataTable to the DataSet. "ds.Tables.Add(yourDataTableName). But you haven't created a datatable.
    Last edited by wes4dbt; Jan 19th, 2018 at 10:55 PM.

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: System.NullReferenceException Error

    I didn't notice that you were mixing and matching a typed and an untyped DataSet, which wes4bt picked up on. You really need to decide which you're going to use first and stick with it. If you have used the Data Source wizard then you have generated a typed DataSet and you should stick with using that. If you want to use an untyoed DataSet then don't use the Data Source wizard at all.

    ADO.NET is the standard data access technology for .NET applications. The functionality of ADO.NET is encapsulated in the System.Data namespace and extended in its child namespaces, e.g. System.Data.SqlClient for SQL Server and System.Data.OleDb for OLE DB data sources. It can also be extended by third parties for other data sources, which has been done for SQLite, MySQL, Oracle and others.

    System.Data contains the DataSet, DataTable, DataColumn, DataRow and DataRelation classes that basically map to databases and their constituent parts. A DataSet is basically an in-memory database. A DataTable is basically an in-memory database table. Just as a database table has columns that define the data rows that contain the data, so a DataTable has a Columns property that is a collection of DataColumns that define the data and a Rows property that is a collection of DataRows that contain the data. A DataSet has a Tables property that is a collection of DataTables. A DataSet also has Relations property that is a collection of DataRelations that define the relationships between the DataTables in the Tables collection. If you are only using one DataTable then it's generally pointless to create a DataSet, much as it's pointless to create an array to contain one String or one Integer. Even if you're using multiple DataTables, it may well be more convenient to use them "loose" unless you are also going to add DataRelations between them in a DataSet.

    System.Data also contains the base functionality for connection and command objects and other types for communicating between your app and a database. Sticking with OleDb, an OleDbConnection represents the connection between the app and the database. The ConnectionString property controls how the connection is made. An OleDbCommand basically represents a SQL statement that can be executed over a connection. The ExecuteScalar, ExecuteReader and ExecuteNonQuery methods all execute the SQL contained in the CommandText property but their behaviour diverges after that. ExecuteScalar returns the value from the first column of the first row of the result set. ExecuteReader returns an OleDbDataReader object that allows you to read the contents of the result set in a forward-only manner. ExecuteNonQuery is intended for SQL Statements that don't produce a result set, i.e. contain no SELECT statement.

    An OleDbDataAdapter is basically a way to group four command objects that encapsulate the CRUD operations for a table. The Fill method of a data adapter executes the SelectCommand of the adapter, which contains a SQL SELECT statement. Internally, it uses a data reader to read the result set and populate a DataTable with the data. It can use a "loose" DataTable, an existing DataTable in a DataSet or it can create a new DataTable in a DataSet. The Update method executes the InsertCommand, UpdateCommand and DeletedCommand of the adapter, which contain an INSERT, UPDATE and DELETE statement respectively, as required to save the changes in a DataTable back to the database. Generally speaking, you will use the same data adapter in both cases. You create an adapter, call Fill to populate a DataTable, edit the data in the DataTable and then call Update on the same data adapter. In certain circumstances, you can use an OleDbCommandBuilder to generate the InsertCommand, UpdateCommand and DeleteCommand for you, although not in all.

    A typed DataSet basically wraps all that functionality up into classes that have additional members that are specific to your data. For instance, instead of getting a DataTable from a DataSet like this:
    vb.net Code:
    1. table = myDataSet.Tables("MyTable")
    you can do this:
    vb.net Code:
    1. table = myDataSet.MyTable
    The difference is that you get help from Intellisense and you can't misspell the name of the table. Similarly, getting a field value from a DataRow alleviates the need to use "magic strings" too, e.g. instead of this:
    vb.net Code:
    1. value = myDataRow("MyColumn")
    you can use this:
    vb.net Code:
    1. value = myDataRow.MyColumn
    As well as the advantages mentioned earlier, you also get the data as the correct type. That's why it's called a "typed" DataSet. In the previous example, you get an Object reference from the DataRow for the value of the field because that same Item property has to support data of any type. In the last example, the MyColumn property is declared as the correct type for the data so it will return a String if that column contains text, an Integer if that column contains integers and so on.

    If you're using a typed DataSet then you also have a table adapter for each DataTable. A table adapter basically wraps a data adapter, meaning that it also wraps all the connection and command functionality. A table adapter has Fill and Update methods, just like a data adapter. In fact, those methods actually call the methods of the same names on a data adapter internally. If you are using a type DataSet then you should basically just create one instance of that DataSet in your form and use that all the time. To get data, you use the appropriate table adapter to populate the appropriate DataTable in that DataSet. To save changes, you use the same table adapter (or perhaps another instance of the same type, the best option depends on the situation) to save the changes from the same DataTable in the same DataSet. If you have dragged a table from the Data Sources window onto your form then the DataSet and the table adapter have been created for you. In fact, the code to retrieve and save the data is already generated for you to. This is that code:
    vb.net Code:
    1. Private Sub TblContactsBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TblContactsBindingNavigatorSaveItem.Click
    2.         Me.Validate()
    3.         Me.TblContactsBindingSource.EndEdit()
    4.         Me.TableAdapterManager.UpdateAll(Me.AddressBookDataSet)
    5.  
    6.     End Sub
    7.  
    8.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    9.         'TODO: This line of code loads data into the 'AddressBookDataSet.tblContacts' table. You can move, or remove it, as needed.
    10.         Me.TblContactsTableAdapter.Fill(Me.AddressBookDataSet.tblContacts)
    11.  
    12.     End Sub
    AddressBookDataSet is your typed DataSet object. AddressBookDataSet.tblContacts is your DataTable.

    The call to Fill in the Load event handler is what retrieves the data from the database. The call to UpdateAll in the Click event handler of the BindingNavigator's Save button is what saves the changes. That UpdateAll method simply calls the Update method of all the table adapters that it's managing, which will be one if you only dragged one table onto the form. You should nee very little change to that code and certainly not the changes that you're making, i.e. adding untyped DataSets. If you want to load data when you click a Button rather than when the form opens, simply move the Fill call to the Click event handler of that Button. Notice the comment provided:
    This line of code loads data into the 'AddressBookDataSet.tblContacts' table. You can move, or remove it, as needed.

  11. #11

    Thread Starter
    Member Logit's Avatar
    Join Date
    Jan 2018
    Posts
    46

    Re: System.NullReferenceException Error

    .
    jmcilhinney (& others) :

    Thank you for responding to my requests for assistance. I truly appreciate your time and input. For various reasons I have concluded that my efforts to date demonstrate the Oledb approach is way over my head. Primarily, when I look at the code, explanations and sample online instructions it appears as a maze in my mind. I'm just not able to grasp the concepts. Perhaps because it does not resemble "legacy VB code" and/or the online instruction I've located assumes too much from the 'student'.

    Understandably, you have a good grasp of the language and this may create questions in your mind why someone else has an ability to do likewise. If this is the case, I wish I could provide an explanation ...

    I located another instructional website covering ADO.Net Database Programming - ADO.NET http://www.visual-basic-tutorials.com/
    The syntax of ADO .Net appears in my mind more of what I am used to viewing and appears to be more understandable to my mind.

    If you go down the page about 1/4, on the right hand side there is a section of instruction entitled : Database Programming - ADO.NET

    Would anyone be kind enough to review the material on those pages and determine for me the completeness of the instruction ? Has the author left out areas that should not have been left out ? If I were to follow this line of instruction ... would I reasonably end up with a functioning database ? Or is there alot more to be covered that has been omitted ? I suspect there is more that has been left out.

    Ultimately I want to find an online free site that will guide me (as though blind ) from beginning to end, resulting in a finished database product. Once I get the basic format down, even if it only includes a database with fields of : Name, Address, City, State, Zip ..... I should be able to add on to that and create the final product I'm seeking.

    More about my background to clear up any questions : My experience with VB5 was 20 -25 years ago and I forgot what little I learned. I've made very good progress with VBA/Excel. So .. comparing VBA syntax to ADO syntax ... there appears in my mind some kind of similarity that is familiar.

    Thank you for taking time to read this. And, if you are willing ... thank you for reviewing the website and providing advice. Perhaps you might know of another website that adheres to my description as 'Database Creation Dummies for the Blind' (no offense intended to anyone).

  12. #12
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: System.NullReferenceException Error

    Quote Originally Posted by Logit View Post
    For various reasons I have concluded that my efforts to date demonstrate the Oledb approach is way over my head. Primarily, when I look at the code, explanations and sample online instructions it appears as a maze in my mind. I'm just not able to grasp the concepts. Perhaps because it does not resemble "legacy VB code" and/or the online instruction I've located assumes too much from the 'student'.

    Understandably, you have a good grasp of the language and this may create questions in your mind why someone else has an ability to do likewise. If this is the case, I wish I could provide an explanation ...

    I located another instructional website covering ADO.Net Database Programming - ADO.NET http://www.visual-basic-tutorials.com/
    The syntax of ADO .Net appears in my mind more of what I am used to viewing and appears to be more understandable to my mind.
    The OleDb approach IS ADO.NET. Like I said, OleDb is simply one implementation of the ADO.NET pattern for use with OLE DB data sources. The System.Data namespace provides the base interfaces and classes, e.g. DbConnection, DbCommand and DbDataAdapter, and then other namespaces contain specific implementations for specific data sources. For example, System.Data.SqlClient contains an implementation specifically for SQL Server, System.Data.OleDb contains an implementation for OLE DB data sources and System.Data.Odbc contains an implementation for ODBC data sources. There are also third party providers, including MySql.Data.MySqlClient for MySQL.

    If you create your own connection, command and data adapter objects from any namespace then you're using ADO.NET. If you create a typed DataSet then you're still using ADO.NET. Like I said, using the wizard to create a typed DataSet generates new types specific to your data. It creates a class that inherits DataSet, a class that inherits DataTable for each table in your database and a table adapter that wraps a data adapter for each table too. The data adapter wrapped by the table adapter is exactly the same as you would use yourself, e.g. it will be an OleDbDataAdapter if you use an Access database or a SqlDataAdapter if you use a SQL Server database.

    So, if you think that OleDb is hard and ADO.NET is not so hard then you are trying to make OleDb something that it's not. Preconceived ideas are a big stumbling for many developers. If you already think that something works a certain way, either consciously or subconsciously, then you will often fail to see how it actually works, even if it's staring you in the face. We've all been there at some point.

    I think that one of the most important points with ADO.NET - and often .NET programming in general, is to take a step back and try to understand what each individual type is intended to achieve. .NET takes the Single Responsibility Principle quite seriously at all levels. It will tend to use multiple specialised types to get a job done rather than one monolithic type. That's because those specialised types can be used in various combinations to achieve various tasks, rather than creating multiple monolithic types that may contain much of the same code. In the case of ADO.NET, you will use multiple types to get data to and from a database. The connection object, e.g. an OleDbConnection, is purely for creating the connection between the app and the database. The command object, e.g. an OleDbCommand, is for executing SQL statements against the database. A data adapter object, e.g. an OleDbDataAdapter, is about performing CRUD operations for a single table, i.e. it groups four commands for executing SELECT, INSERT, UPDATE and DELETE operations. A data reader is for read the result set of a query, one record at a time, forward-only. A DataSet is basically an in-memory representation of a database or part there of. A DataTable is basically an in-memory representation of a database table. If you understand the role of each type, you can then break your task down into parts and determine which type is appropriate to accomplish which part.

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: System.NullReferenceException Error

    Quote Originally Posted by Logit View Post
    Would anyone be kind enough to review the material on those pages and determine for me the completeness of the instruction ? Has the author left out areas that should not have been left out ? If I were to follow this line of instruction ... would I reasonably end up with a functioning database ? Or is there alot more to be covered that has been omitted ? I suspect there is more that has been left out.
    There's always more to learn. At a glance, that site looks pretty good. I just wanted to point out that it is using SqlClient for SQL Server databases. The instruction would be basically the same for an OLE DB data source except that it would be using an OleDbConnection instead of a SqlConnection, an OleDbCommand instead of a SqlCommand and so on. If you're not already aware, OLE DB is a standard interface for databases created by Microsoft. The ides is that an application only has to understand OLE DB and it can then connect to any data source for which an OLE DB provider exists. There are OLE DB providers for a huge number of data sources, including SQL Server (yes, you can connect SQL Server directly using SqlClient or via an OLE DB provider), but the most common you'll find around here is Access. As a general rule, you should use an ADO.NET provider that is specific to your data if you can, then use OleDb if you can be data-source-specific, then use Odbc if you must.

  14. #14
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,181

    Re: System.NullReferenceException Error

    I think one of the major problems is people, especially people with some programming knowledge, think they can skip the beginning lessons and try to start in the middle. I've always found that programming skills are like math skills and you use the skills from Chapter 1 to help you through Chapter 2. The fact you didn't know Oledb was ADO .Net shows your trying to use a skill but have know real understanding of what your working with.

    I'm not trying to pick on you but I'm just trying to point out the necessity to start from the beginning. One of the hardest things for me was I didn't really understand the terminology. I remember jmc explaining a concept or reason why my code wasn't working and not understanding what he was saying. Object type, Reference Objects, Method, Namespace ....., I only had a vague idea what these terms meant. And I'd been programming for 20+ years before I started working in VB .Net.

  15. #15

    Thread Starter
    Member Logit's Avatar
    Join Date
    Jan 2018
    Posts
    46

    Re: System.NullReferenceException Error

    .
    Thank you for your input. It is very much appreciated.

    One of the problems I have experienced my whole life is the inability to learn strictly through 'book learning'. I am not discounting your advice ... believe me ... it's just that I need to be able to get my hands on the project - play with the different parts of it - break it and fix it. The 'book learning' for me comes as I'm learning what things do and how to apply the function in various ways if there are any. Reading, memorizing and recalling terms/definitions/facts, etc. has always been a real challenge for me. (I think my mother dropped me on my head as an infant and refused to tell me.) For example: If I were to meet you for the first time, after we parted ways, within 15 minutes or less I would not be able to recall your name. Go figure ! In this situation, I would need to interact with you several times before I would begin to recall your name.

    Talk about challenges in life, huh ?

    During my career years I always found a way to politely interact with peers without letting on. I found a way to word conversations so saying the other person's name was not necessary. Then, after several occasions of interaction that hurdle was overcome.

    Anyway .... that's my story. Always wished my mind functioned a lot better than it does. Can't wait to see what happens when I'm in my 70's or 80's when the cognitive functions oftentimes decline for most folks.

    Enough of the conversation.


    Here is a project I've been playing with today trying to understand. There were a number of errors that have already been corrected. However there remains one error that I can't correct.

    Error Message = "Object variable or With block variable not set."

    Here is the section of involved code :

    Code:
    Imports System.Data.SqlClient
    Imports System.Text.RegularExpressions
    
    Public Class FillOrCancel
    
        ' Storage for OrderID.  
        Private parsedOrderID As Integer
        Private txtOrderID As Object  '----------------------------------<<<<<<<<<<<<<<<<<<< Object variable defined here - As I understand it.
        Private dtpFillDate As Object
    
        ''' <summary>
        ''' Verifies that OrderID is valid.
        ''' </summary>
        Private Function IsOrderIDValid() As Boolean
            'Dim txtOrderID As Object
            ' Check for input in the Order ID text box.
    
            If txtOrderID.Text = "" Then   '----------------------------------------<<<<<<<<<<<<<<< Error here
                MessageBox.Show("Please specify the Order ID.")
                Return False
    
                ' Check for characters other than integers.  
            ElseIf Regex.IsMatch(txtOrderID.Text, "^\D*$") Then
                ' Show message and clear input.  
                MessageBox.Show("Please specify integers only.")
                txtOrderID.Clear()
                Return False
            Else
                ' Convert the text in the text box to an integer to send to the database.  
                parsedOrderID = Int32.Parse(txtOrderID.Text)
                Return True
            End If
        End Function
    The error is indicated with "----<<<<<"

    What would you suggest ? Let me know if you require more information/code.


    Thank you !

  16. #16

    Thread Starter
    Member Logit's Avatar
    Join Date
    Jan 2018
    Posts
    46

    Re: System.NullReferenceException Error

    .
    After doing some more digging .... in the Properties window, VB says txtOrderID is not a valid name and wants to name the text box tctOrderID.

    So, I've tried changing the name to txtOrderId and get an error - then tried using tctOrderId in the syntax of the form .. still get an error.

    Now what ?

  17. #17
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: System.NullReferenceException Error

    On the first highlighted line, you are declaring a variable. A variable is NOT an object. The fact that you have a garage does not mean that you have a car. A variable is just somewhere to put an object. All variables are Nothing by default. If you want the variable to not be Nothing, you have to assign something to it. If you expect a variable to refer to a Textbox object, which appears to be the case there, then you have to actually create a TextBox object and assign it to the variable. This is exactly the same thing as we discussed earlier with the data adapter. An OleDbDataAdapter variable is NOT an object. It is Nothing by default, like any other variable. If you want an object you have to create one and if you expect a variable to refer to that object then you need to assign the object to the variable. This is JUST a variable declaration:
    vb.net Code:
    1. Dim var As SomeType
    This code creates an object and assigns it to that variable:
    vb.net Code:
    1. Dim var As SomeType
    2.  
    3. var = New SomeType
    That 'New' keyword invokes a constructor of the SomeType class. The New method(s) you see in your code is the constructor. That code can be condensed into a single line if you want to create the object immediately:
    vb.net Code:
    1. Dim var As SomeType = New SomeType
    and you can condense that further by using this shorthand:
    vb.net Code:
    1. Dim var As New SomeType
    If you don't have a 'New' keyword then you are not creating a new object yourself. You might call a method that returns an object, in which case you must perform an assignment:
    vb.net Code:
    1. Dim var As SomeType = SomeFunction()

  18. #18
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: System.NullReferenceException Error

    Also, if you want a variable to refer to a TextBox object then it should be declared as type TextBox, not type Object. You'd only use type Object if you don't know at design time exactly what type of object will be assigned to the variable at run time.

  19. #19
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: System.NullReferenceException Error

    You show us code where you're declaring the variable yourself, then you tell us that you are looking in the properties window, meaning that you must have added a control in the designer. If you add a control in the designer then the IDE automatically declares a variable with the name you specify. You shouldn't be declaring the same one yourself. You need to get straight in your head what you're trying to accomplish and it might not be a bad idea to explain it to us too, rather than assuming that we can work it out from code that doesn't do it.

  20. #20

    Thread Starter
    Member Logit's Avatar
    Join Date
    Jan 2018
    Posts
    46

    Re: [RESOLVED] System.NullReferenceException Error

    .
    Thank you for the pointers.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width