Rectangle 27 20

Step #2: Create an instance of Select2

<input name="mySelect2" type="hidden" id="mySelect2">
$("#mySelect2").select2({
      placeholder: "My Select 2",
      multiple: false,
      minimumInputLength: 1,
      ajax: {
          url: "/elements/all",
          dataType: 'json',
          quietMillis: 250,
          data: function(term, page) {
              return {
                  q: term,
              };
          },
          results: function(data, page) {
              return {results: data};
          },
          cache: true
      },
      formatResult: function(element){
          return element.text + ' (' + element.id + ')';
      },
      formatSelection: function(element){
          return element.text + ' (' + element.id + ')';
      },
      escapeMarkup: function(m) {
          return m;
      }
});
$("#mySelect2").select2('data', { id:"elementID", text: "Hello!"});

If you use select2 without AJAX you can do as follow:

<select name="mySelect2" id="mySelect2">
  <option value="0">One</option>
  <option value="1">Two</option>
  <option value="2">Three</option>
</select>
/* //////////// "One" will be the selected option */
$('[name=mySelect2]').val("0");

You can also do so:

$("#mySelect2").select2("val", "0");

For select2 v4 you can append directly an option/s as follow:

<select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]">
    <option value="TheID" selected="selected">The text</option>                                                                   
</select>

Or with JQuery:

var $newOption = $("<option></option>").val("TheID").text("The text")

$("#myMultipleSelect2").append($newOption).trigger('change');
$("select123455").val(5).trigger('change');

This won't work on Select2 v4 - probably why the downvote. It looks like a bug.

javascript - How to set selected value of jquery select2? - Stack Over...

javascript php jquery ajax jquery-select2
Rectangle 27 13

You can't create an instance of an interface

Correct. You create an instance of an object implementing an interface:

IAuditable myUser = new User();

No where in the code does it define which IAudit applies to which IAuditable

You can't do this directly with just one interface. You will need to rethink your design.

You can use a open generic type in the interface and implement it with closed types:

public interface IAudit<T> {
    DateTime DateCreated { get; set; }
}

public class UserAudit : IAudit<User> {
    public string UserName { get; set; }
    public DateTime DateCreated { get; set; }

    public UserAdit(User user) {
        UserName = user.UserName;
    }
}

I can't specify that the IAudit interface must have a constructor which takes an IAuditable

Correct, you can't. See here. You need to create such a constructor on the implementers.

Useful answer, useful info for OP, but still focuses too much on the c#/.net specifics to get an upvote from me ... for now. Tridus' addresses the real issue IMO. Still, useful info for OP.

c# - Creating an Instance of an Interface - Stack Overflow

c# interface
Rectangle 27 65

You can for example create an instance of List<object>, which implements IEnumerable<object>. Example:

List<object> list = new List<object>();
list.Add(1);
list.Add(4);
list.Add(5);

IEnumerable<object> en = list;
CallFunction(en);

Given that the question shows the use of generics, given an example of a type that doesn't implement the generic IEnumerable<T> is a bad idea IMO.

Any problem with using CallFunction(list.AsEnumerable()) instead of IEnumerable<object> en = list;...

c# - IEnumerable a = new IEnumerable(); Can i do this?... c#
Rectangle 27 83

The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.

However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.

You can do this to execute a static method:

MyObject.staticMethod();//Simply refers to the class's static code
MyObject obj = new MyObject();//Create an instance
obj.nonstaticMethod();//Refer to the instance's class's code

On a deeper level, when the compiler puts a class together, it contains several pointers to methods. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.

@Rohan Another good way of looking at it is that anything static(a class, method, or field) doesn't really belong to anything, it just hangs out in the class for organizational purposes.

in addition static fields are used as data objects(one which holds the data and therefore cant change but you can manipulate data inside it.).Static methods can only be called upon static fields and henceforth carries the same notion of staying constant or not changeing or not instantiating !!

@user2416728 Your comment is very confused. Static fields can be changed, but their scope is global to their execution environment. Therefore, any code that has access to said field has access to the same data. This is not equivalent to that data staying constant (unless a 'final' modifier is used).

java - Difference between Static methods and Instance methods - Stack ...

java static static-methods non-static
Rectangle 27 91

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

Foo.bar will work, but self.bar creates an instance variable, not a static one.

bedwyr, "print self.bar" will not create any instance variables (although assigning to self.bar will).

@Constantin -- I didn't realize that, it's an interesting distinction. Thanks for the correction :-)

But if you don't intend for there to be an ivar, its clearer to use Foo.classmember.

when using static variables, it's a good idea to read the gotchas from here: stackoverflow.com/questions/68645/ . @Constantin gives one of the many gotchas.

In Python how can I access "static" class variables within class metho...

python
Rectangle 27 38

The error is because you're trying to create an instance of the interface.

List<ListItem> allFaqs = new List<ListItem>();
IList<ListItem> allFaqs = new List<ListItem>();

and it should compile.

You'll obviously have to change the rest of your code to suit too.

saved me a lot of time, thanks :)

generics - Initialize IList C# - Stack Overflow

c# generics
Rectangle 27 88

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

Foo.bar will work, but self.bar creates an instance variable, not a static one.

bedwyr, "print self.bar" will not create any instance variables (although assigning to self.bar will).

@Constantin -- I didn't realize that, it's an interesting distinction. Thanks for the correction :-)

But if you don't intend for there to be an ivar, its clearer to use Foo.classmember.

when using static variables, it's a good idea to read the gotchas from here: stackoverflow.com/questions/68645/ . @Constantin gives one of the many gotchas.

In Python how can I access "static" class variables within class metho...

python
Rectangle 27 82

What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:

Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);
Date
private Calendar startTime;
private long duration;
private long startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuration() {
        return this.duration;
}

In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

Java's date/time implementation is so shitty that I'm not sure what's worse - keeping JodaTime - even though time computation is a very small part of my app's overall functionality - or switching to Date/Calendar and spending hours wading through the half-assed mess that should've been a well-implemented, solid component.

Date object to Calendar [Java] - Stack Overflow

java date calendar
Rectangle 27 82

What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:

Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);
Date
private Calendar startTime;
private long duration;
private long startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuration() {
        return this.duration;
}

In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

Java's date/time implementation is so shitty that I'm not sure what's worse - keeping JodaTime - even though time computation is a very small part of my app's overall functionality - or switching to Date/Calendar and spending hours wading through the half-assed mess that should've been a well-implemented, solid component.

Date object to Calendar [Java] - Stack Overflow

java date calendar
Rectangle 27 236

You are likely using the wrong username to login:

  • most Ubuntu images have a user ubuntu
ec2-user
  • most Debian images have either root or admin
ssh -l USERNAME_HERE -i .ssh/yourkey.pem public-ec2-host

The error message says it all: the .pem cert file is not protected enough. Do chmod 400 xyz.pem as suggested below.

Permission denied (publickey).

I found the issue - I wasn't using the same key I created the instance with

This is not the solution - the file permissions on the downloaded key file are 844 by default. should be 400 chmod 500 <path_to_pem_file> should do it.

authentication - Trying to SSH into an Amazon Ec2 instance - permissio...

amazon-web-services authentication ssh amazon-ec2 permissions
Rectangle 27 236

You are likely using the wrong username to login:

  • most ubuntu images have a user ubuntu
  • most Ubuntu images have a user ubuntu
ec2-user
  • most Debian images have either root or admin
ssh -l USERNAME_HERE -i .ssh/yourkey.pem public-ec2-host

The error message says it all: the .pem cert file is not protected enough. Do chmod 400 xyz.pem as suggested below.

Permission denied (publickey).

I found the issue - I wasn't using the same key I created the instance with

This is not the solution - the file permissions on the downloaded key file are 844 by default. should be 400 chmod 500 <path_to_pem_file> should do it.

authentication - Trying to SSH into an Amazon Ec2 instance - permissio...

amazon-web-services authentication ssh amazon-ec2 permissions
Rectangle 27 236

You are likely using the wrong username to login:

  • most Ubuntu images have a user ubuntu
ec2-user
  • most Debian images have either root or admin
ssh -l USERNAME_HERE -i .ssh/yourkey.pem public-ec2-host

The error message says it all: the .pem cert file is not protected enough. Do chmod 400 xyz.pem as suggested below.

Permission denied (publickey).

I found the issue - I wasn't using the same key I created the instance with

This is not the solution - the file permissions on the downloaded key file are 844 by default. should be 400 chmod 500 <path_to_pem_file> should do it.

authentication - Trying to SSH into an Amazon Ec2 instance - permissio...

amazon-web-services authentication ssh amazon-ec2 permissions
Rectangle 27 351

In order to create an instance of a generic type in a function you must constrain it with the "new" flag.

However that will only work when you want to call the constructor which has no parameters. Not the case here. Instead you'll have to provide another parameter which allows for the creation of object based on parameters. The easiest is a function.

public static string GetAllItems<T>(..., Func<ListItem,T> del) {
  ...
  List<T> tabListItems = new List<T>();
  foreach (ListItem listItem in listCollection) 
  {
    tabListItems.Add(del(listItem));
  }
  ...
}

You can then call it like so

GetAllItems<Foo>(..., l => new Foo(l));

How would this work when called internally from a generic class? I have posted my code in an answer below. I don't know the concrete class internally, as it's a generic class. Is there a way round this. I dont want to use the other suggestion of using property initialiser syntax as that will bypass the logic I have in the constructor

+1 nice work around for the constructor limitations. Be nice if future version would support parameterized constructor constraints

This is currently one of the most annoying limitations of C#. I would like to make my classes immutable: Having just private setters would make the class impossible to be in an invalid state by side effects. I also like to use that Func and lambda, but I know it still is a problem in bussiness world as generally programmers don't know lambdas yet and this makes your class harder to understand.

+1. Annoying, but better than nothing.

Thanks. In my case I know the constructor's argument(s) when I call the method, I just needed to get around the Type parameter's limitation that it could not be constructed with parameters, so I used a thunk. The thunk is an optional parameter to the method, and I only use it if provided: T result = thunk == null ? new T() : thunk(); The benefit of this for me is consolidating the logic of T creation in one place rather than sometimes creating T inside and sometimes outside of the method.

.net - Passing arguments to C# generic new() of templated type - Stack...

c# .net generics new-operator
Rectangle 27 350

In order to create an instance of a generic type in a function you must constrain it with the "new" flag.

However that will only work when you want to call the constructor which has no parameters. Not the case here. Instead you'll have to provide another parameter which allows for the creation of object based on parameters. The easiest is a function.

public static string GetAllItems<T>(..., Func<ListItem,T> del) {
  ...
  List<T> tabListItems = new List<T>();
  foreach (ListItem listItem in listCollection) 
  {
    tabListItems.Add(del(listItem));
  }
  ...
}

You can then call it like so

GetAllItems<Foo>(..., l => new Foo(l));

How would this work when called internally from a generic class? I have posted my code in an answer below. I don't know the concrete class internally, as it's a generic class. Is there a way round this. I dont want to use the other suggestion of using property initialiser syntax as that will bypass the logic I have in the constructor

This is currently one of the most annoying limitations of C#. I would like to make my classes immutable: Having just private setters would make the class impossible to be in an invalid state by side effects. I also like to use that Func and lambda, but I know it still is a problem in bussiness world as generally programmers don't know lambdas yet and this makes your class harder to understand.

Thanks. In my case I know the constructor's argument(s) when I call the method, I just needed to get around the Type parameter's limitation that it could not be constructed with parameters, so I used a thunk. The thunk is an optional parameter to the method, and I only use it if provided: T result = thunk == null ? new T() : thunk(); The benefit of this for me is consolidating the logic of T creation in one place rather than sometimes creating T inside and sometimes outside of the method.

.net - Passing arguments to C# generic new() of templated type - Stack...

c# .net generics new-operator
Rectangle 27 7

if you want to create other instance as needed.do this:

+ (MyClass *)sharedInstance
{
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MyClass alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone
{
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [super allocWithZone:zone];
    });
    return sharedInstance;
}

True/False: The dispatch_once() bit means that you won't get additional instances, even in the first example...?

@Olie: False, because client code can do [[MyClass alloc] init] and bypass the sharedInstance access. DongXu, you should look at Peter Hosey's Singleton article. If you're going to override allocWithZone: to prevent more instances from being created, you also should override init to prevent the shared instance from being re-initialized.

Ok, that's what I thought, hence the allocWithZone: version. Thx.

This completely breaks the contract of allocWithZone.

ios - How do I implement an Objective-C singleton that is compatible w...

objective-c ios singleton automatic-ref-counting
Rectangle 27 68

You could create an instance of the class you want to call the method on, e.g.

new Foo().nonStaticMethod();

And probably completely pointless. The purpose of a non-static method is to interrogate or alter the state of an object which is signicant to the application. Creating a temporary object cannot possibly meet that objective. Either the calling method needs to be non-static or there is something seriously wrong with the design.

calling non-static method in static method in Java - Stack Overflow

java static non-static
Rectangle 27 24

Would a Javascript interpreter really create an instance of the function per iteration?

It has to because it doesn't know if the function object will be modified elsewhere. Remember that functions are standard JavaScript objects, so they can have properties like any other object. When you do this:

card = $('<div>').bind('isPopulated', function (ev) { ... })

for all you know, bind could modify the object, for example:

function bind(str, fn) {
  fn.foo = str;
}

Clearly this would result in wrong behaviour if the function object was shared across all iterations.

Very, very good point about the function getting modified!

Note that just because separate Function objects are created, it doesn't mean they don't share the same code, at least on some JavaScript engines: groups.google.com/group/v8-users/browse_thread/thread/

JSlint error 'Don't make functions within a loop.' leads to question a...

javascript jslint
Rectangle 27 24

Would a Javascript interpreter really create an instance of the function per iteration?

It has to because it doesn't know if the function object will be modified elsewhere. Remember that functions are standard JavaScript objects, so they can have properties like any other object. When you do this:

card = $('<div>').bind('isPopulated', function (ev) { ... })

for all you know, bind could modify the object, for example:

function bind(str, fn) {
  fn.foo = str;
}

Clearly this would result in wrong behaviour if the function object was shared across all iterations.

Very, very good point about the function getting modified!

Note that just because separate Function objects are created, it doesn't mean they don't share the same code, at least on some JavaScript engines: groups.google.com/group/v8-users/browse_thread/thread/

JSlint error 'Don't make functions within a loop.' leads to question a...

javascript jslint
Rectangle 27 24

Would a Javascript interpreter really create an instance of the function per iteration?

It has to because it doesn't know if the function object will be modified elsewhere. Remember that functions are standard JavaScript objects, so they can have properties like any other object. When you do this:

card = $('<div>').bind('isPopulated', function (ev) { ... })

for all you know, bind could modify the object, for example:

function bind(str, fn) {
  fn.foo = str;
}

Clearly this would result in wrong behaviour if the function object was shared across all iterations.

Very, very good point about the function getting modified!

Note that just because separate Function objects are created, it doesn't mean they don't share the same code, at least on some JavaScript engines: groups.google.com/group/v8-users/browse_thread/thread/

JSlint error 'Don't make functions within a loop.' leads to question a...

javascript jslint
Rectangle 27 249

Examples and Remedies

The NullReference Exception for Visual Basic is no different from the one in C#. After all, they are both reporting the same exception defined in the .NET Framework which they both use. Causes unique to Visual Basic are rare (perhaps only one).

This answer will use Visual Basic terms, syntax, and context. The examples used come from a large number of past Stack Overflow questions. This is to maximize relevance by using the kinds of situations often seen in posts. A bit more explanation is also provided for those who might need it. An example similar to yours is very likely listed here.

  • This is concept-based: there is no code for you to paste into your project. It is intended to help you understand what causes a NullReferenceException (NRE), how to find it, how to fix it, and how to avoid it. An NRE can be caused many ways so this is unlikely to be your sole encounter.
  • The examples (from Stack Overflow posts) do not always show the best way to do something in the first place.
  • Typically, the simplest remedy is used.

The message "Object not set to an instance of Object" means you are trying to use an object which has not been initialized. This boils down to one of these:

  • Your code declared an object variable, but it did not initialize it (create an instance or 'instantiate' it)
  • Something which your code assumed would initialize an object, did not

Since the problem is an object reference which is Nothing, the answer is to examine them to find out which one. Then determine why it is not initialized. Hold the mouse over the various variables and Visual Studio (VS) will show their values - the culprit will be Nothing.

You should also remove any Try/Catch blocks from the relevant code, especially ones where there is nothing in the Catch block. This will cause your code to crash when it tries to use an object which is Nothing. This is what you want because it will identify the exact location of the problem, and allow you to identify the object causing it.

A MsgBox in the Catch which displays Error while... will be of little help. This method also leads to very bad Stack Overflow questions, because you can't describe the actual exception, the object involved or even the line of code where it happens.

Locals Window

Once you know what and where the problem is, it is usually fairly easy to fix and faster than posting a new question.

Dim reg As CashRegister
...
TextBox1.Text = reg.Amount         ' NRE

The problem is that Dim does not create a CashRegister object; it only declares a variable named reg of that Type. Declaring an object variable and creating an instance are two different things.

The New operator can often be used to create the instance when you declare it:

Dim reg As New CashRegister        ' [New] creates instance, invokes the constructor

' Longer, more explicit form:
Dim reg As CashRegister = New CashRegister
Private reg As CashRegister         ' Declare
  ...
reg = New CashRegister()            ' Create instance

Note: Do not use Dim again in a procedure, including the constructor (Sub New):

Private reg As CashRegister
'...

Public Sub New()
   '...
   Dim reg As New CashRegister
End Sub

This will create a local variable, reg, which exists only in that context (sub). The reg variable with module level Scope which you will use everywhere else remains Nothing.

New
NullReference Exceptions

Visual Basic tries to make the process clear repeatedly using New: Using the New Operator creates a new object and calls Sub New -- the constructor -- where your object can perform any other initialization.

To be clear, Dim (or Private) only declares a variable and its Type. The Scope of the variable - whether it exists for the entire module/class or is local to a procedure - is determined by where it is declared. Private | Friend | Public defines the access level, not Scope.

Private arr as String()

This array has only been declared, not created. There are several ways to initialize an array:

Private arr as String() = New String(10){}
' or
Private arr() As String = New String(10){}

' For a local array (in a procedure) and using 'Option Infer':
Dim arr = New String(10) {}

Note: Beginning with VS 2010, when initializing a local array using a literal and Option Infer, the As <Type> and New elements are optional:

Dim myDbl As Double() = {1.5, 2, 9.9, 18, 3.14}
Dim myDbl = New Double() {1.5, 2, 9.9, 18, 3.14}
Dim myDbl() = {1.5, 2, 9.9, 18, 3.14}

The data Type and array size are inferred from the data being assigned. Class/Module level declarations still require As <Type> with Option Strict:

Private myDoubles As Double() = {1.5, 2, 9.9, 18, 3.14}

Example: Array of class objects

Dim arrFoo(5) As Foo

For i As Integer = 0 To arrFoo.Count - 1
   arrFoo(i).Bar = i * 10       ' Exception
Next

The array has been created, but the Foo objects in it have not.

For i As Integer = 0 To arrFoo.Count - 1
    arrFoo(i) = New Foo()         ' Create Foo instance
    arrFoo(i).Bar = i * 10
Next

Using a List(Of T) will make it quite difficult to have an element without a valid object:

Dim FooList As New List(Of Foo)     ' List created, but it is empty
Dim f As Foo                        ' Temporary variable for the loop

For i As Integer = 0 To 5
    f = New Foo()                    ' Foo instance created
    f.Bar =  i * 10
    FooList.Add(f)                   ' Foo object added to list
Next
Private myList As List(Of String)
..
myList.Add("ziggy")           ' NullReference

You get the same exception for the same reason - myList was only declared, but no instance created. The remedy is the same:

myList = New List(Of String)

' Or create an instance when declared:
Private myList As New List(Of String)

A common oversight is a class which uses a collection Type:

Public Class Foo
    Private barList As List(Of Bar)

    Friend Function BarCount As Integer
        Return barList.Count
    End Function

    Friend Sub AddItem(newBar As Bar)
        If barList.Contains(newBar) = False Then
            barList.Add(newBar)
        End If
    End Function

Either procedure will result in an NRE, because barList is only declared, not instantiated. Creating an instance of Foo will not also create an instance of the internal barList. It may have been the intent to do this in the constructor:

Public Sub New         ' Constructor
    ' Stuff to do when a new Foo is created...
    barList = New List(Of Bar)
End Sub
Public Sub New()
    ' Creates another barList local to this procedure
     Dim barList As New List(Of Bar)
End Sub
List(Of T)

Working with databases presents many opportunities for a NullReference because there can be many objects (Command, Connection, Transaction, Dataset, DataTable, DataRows....) in use at once. Note: It does not matter which data provider you are using -- MySQL, SQL Server, OleDB, etc. -- the concepts are the same.

Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim MaxRows As Integer

con.Open()
Dim sql = "SELECT * FROM tblfoobar_List"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "foobar")
con.Close()

MaxRows = ds.Tables("foobar").Rows.Count      ' Error

As before, the ds Dataset object was declared, but an instance was never created. The DataAdapter will fill an existing DataSet, not create one. In this case, since ds is a local variable, the IDE warns you that this might happen:

When declared as a module/class level variable, as appears to be the case with con, the compiler can't know if the object was created by an upstream procedure. Do not ignore warnings.

Dim ds As New DataSet
ds = New DataSet
da = New OleDBDataAdapter(sql, con)
da.Fill(ds, "Employees")

txtID.Text = ds.Tables("Employee").Rows(0).Item(1)
txtID.Name = ds.Tables("Employee").Rows(0).Item(2)

A typo is a problem here: Employees vs Employee. There was no DataTable named "Employee" created, so a NullReferenceException results trying to access it. Another potential problem is assuming there will be Items which may not be so when the SQL includes a WHERE clause.

Since this uses one table, using Tables(0) will avoid spelling errors. Examining Rows.Count can also help:

Fill is a function returning the number of Rows affected which can also be tested:

If da.Fill(ds, "Employees") > 0 Then...
Dim da As New OleDb.OleDbDataAdapter("SELECT TICKET.TICKET_NO,
        TICKET.CUSTOMER_ID, ... FROM TICKET_RESERVATION AS TICKET INNER JOIN
        FLIGHT_DETAILS AS FLIGHT ... WHERE [TICKET.TICKET_NO]= ...", con)
Dim ds As New DataSet
da.Fill(ds)

If ds.Tables("TICKET_RESERVATION").Rows.Count > 0 Then

The DataAdapter will provide TableNames as shown in the previous example, but it does not parse names from the SQL or database table. As a result, ds.Tables("TICKET_RESERVATION") references a non-existent table.

The Remedy is the same, reference the table by index:

If ds.Tables(0).Rows.Count > 0 Then
If myFoo.Bar.Items IsNot Nothing Then
   ...

The code is only testing Items while both myFoo and Bar may also be Nothing. The remedy is to test the entire chain or path of objects one at a time:

If (myFoo IsNot Nothing) AndAlso
    (myFoo.Bar IsNot Nothing) AndAlso
    (myFoo.Bar.Items IsNot Nothing) Then
    ....

AndAlso is important. Subsequent tests will not be performed once the first False condition is encountered. This allows the code to safely 'drill' into the object(s) one 'level' at a time, evaluating myFoo.Bar only after (and if) myFoo is determined to be valid. Object chains or paths can get quite long when coding complex objects:

myBase.myNodes(3).Layer.SubLayer.Foo.Files.Add("somefilename")

It is not possible to reference anything 'downstream' of a null object. This also applies to controls:

myWebBrowser.Document.GetElementById("formfld1").InnerText = "some value"

Here, myWebBrowser or Document could be Nothing or the formfld1 element may not exist.

Dim cmd5 As New SqlCommand("select Cartons, Pieces, Foobar " _
     & "FROM Invoice where invoice_no = '" & _
     Me.ComboBox5.SelectedItem.ToString.Trim & "' And category = '" & _
     Me.ListBox1.SelectedItem.ToString.Trim & "' And item_name = '" & _
     Me.ComboBox2.SelectedValue.ToString.Trim & "' And expiry_date = '" & _
     Me.expiry.Text & "'", con)

Among other things, this code does not anticipate that the user may not have selected something in one or more UI controls. ListBox1.SelectedItem may well be Nothing, so ListBox1.SelectedItem.ToString will result in an NRE.

Validate data before using it (also use Option Strict and SQL parameters):

Dim expiry As DateTime         ' for text date validation
If (ComboBox5.SelectedItems.Count > 0) AndAlso
    (ListBox1.SelectedItems.Count > 0) AndAlso
    (ComboBox2.SelectedItems.Count > 0) AndAlso
    (DateTime.TryParse(expiry.Text, expiry) Then

    '... do stuff
Else
    MessageBox.Show(...error message...)
End If
(ComboBox5.SelectedItem IsNot Nothing) AndAlso...

This is a fairly common way to get an NRE. In C#, depending on how it is coded, the IDE will report that Controls does not exist in the current context, or "cannot reference non-static member". So, to some extent, this is a VB-only situation. It is also complex because it can result in a failure cascade.

Form
Controls
  • The Array will contain five elements of Nothing
  • The somevar assignment will result in an immediate NRE because Nothing doesn't have a .Text property

Referencing array elements later will result in an NRE. If you do this in Form_Load, due to an odd bug, the IDE may not report the exception when it happens. The exception will pop up later when your code tries to use the array. This "silent exception" is detailed in this post. For our purposes, the key is that when something catastrophic happens while creating a form (Sub New or Form Load event), exceptions may go unreported, the code exits the procedure and just displays the form.

Since no other code in your Sub New or Form Load event will run after the NRE, a great many other things can be left uninitialized.

Sub Form_Load(..._
   '...
   Dim name As String = NameBoxes(2).Text        ' NRE
   ' ...
   ' More code (which will likely not be executed)
   ' ...
End Sub

Note this applies to any and all control and component references making these illegal where they are:

Public Class Form1

    Private myFiles() As String = Me.OpenFileDialog1.FileName & ...
    Private dbcon As String = OpenFileDialog1.FileName & ";Jet Oledb..."
    Private studentName As String = TextBox13.Text

It is curious that VB does not provide a warning, but the remedy is to declare the containers at the form level, but initialize them in form load event handler when the controls do exist. This can be done in Sub New as long as your code is after the InitializeComponent call:

' Module level declaration
Private NameBoxes as TextBox()
Private studentName As String

' Form Load, Form Shown or Sub New:
'
' Using the OP's approach (illegal using OPTION STRICT)
NameBoxes = New TextBox() {Me.Controls("TextBox1"), Me.Controls("TestBox2"), ...)
studentName = TextBox32.Text           ' For simple control references

The array code may not be out of the woods yet. Any controls which are in a container control (like a GroupBox or Panel) will not be found in Me.Controls; they will be in the Controls collection of that Panel or GroupBox. Nor will a control be returned when the control name is misspelled ("TeStBox2"). In such cases, Nothing will again be stored in those array elements and an NRE will result when you attempt to reference it.

These should be easy to find now that you know what you are looking for:

"Button2" resides on a Panel

Rather than indirect references by name using the form's Controls collection, use the control reference:

' Declaration
Private NameBoxes As TextBox()

' Initialization -  simple and easy to read, hard to botch:
NameBoxes = New TextBox() {TextBox1, TextBox2, ...)

' Initialize a List
NamesList = New List(Of TextBox)({TextBox1, TextBox2, TextBox3...})
' or
NamesList = New List(Of TextBox)
NamesList.AddRange({TextBox1, TextBox2, TextBox3...})
Private bars As New List(Of Bars)        ' Declared and created

Public Function BarList() As List(Of Bars)
    bars.Clear
    If someCondition Then
        For n As Integer = 0 to someValue
            bars.Add(GetBar(n))
        Next n
    Else
        Exit Function
    End If

    Return bars
End Function

This is a case where the IDE will warn you that 'not all paths return a value and a NullReferenceException may result'. You can suppress the warning, by replacing Exit Function with Return Nothing, but that does not solve the problem. Anything which tries to use the return when someCondition = False will result in an NRE:

bList = myFoo.BarList()
For Each b As Bar in bList      ' EXCEPTION
      ...

Replace Exit Function in the function with Return bList. Returning an empty List is not the same as returning Nothing. If there is a chance that a returned object can be Nothing, test before using it:

bList = myFoo.BarList()
 If bList IsNot Nothing Then...

A badly implemented Try/Catch can hide where the problem is and result in new ones:

Dim dr As SqlDataReader
Try
    Dim lnk As LinkButton = TryCast(sender, LinkButton)
    Dim gr As GridViewRow = DirectCast(lnk.NamingContainer, GridViewRow)
    Dim eid As String = GridView1.DataKeys(gr.RowIndex).Value.ToString()
    ViewState("username") = eid
    sqlQry = "select FirstName, Surname, DepartmentName, ExtensionName, jobTitle,
             Pager, mailaddress, from employees1 where username='" & eid & "'"
    If connection.State <> ConnectionState.Open Then
        connection.Open()
    End If
    command = New SqlCommand(sqlQry, connection)

    'More code fooing and barring

    dr = command.ExecuteReader()
    If dr.Read() Then
        lblFirstName.Text = Convert.ToString(dr("FirstName"))
        ...
    End If
    mpe.Show()
Catch

Finally
    command.Dispose()
    dr.Close()             ' <-- NRE
    connection.Close()
End Try

This is a case of an object not being created as expected, but also demonstrates the counter usefulness of an empty Catch.

There is an extra comma in the SQL (after 'mailaddress') which results in an exception at .ExecuteReader. After the Catch does nothing, Finally tries to perform clean up, but since you cannot Close a null DataReader object, a brand new NullReferenceException results.

An empty Catch block is the devil's playground. This OP was baffled why he was getting an NRE in the Finally block. In other situations, an empty Catch may result in something else much further downstream going haywire and cause you to spend time looking at the wrong things in the wrong place for the problem. (The "silent exception" described above provides the same entertainment value.)

Don't use empty Try/Catch blocks - let the code crash so you can a) identify the cause b) identify the location and c) apply a proper remedy. Try/Catch blocks are not intended to hide exceptions from the person uniquely qualified to fix them - the developer.

For Each row As DataGridViewRow In dgvPlanning.Rows
    If Not IsDBNull(row.Cells(0).Value) Then
        ...
IsDBNull
System.DBNull

The System.DBNull value indicates that the Object represents missing or non-existent data. DBNull is not the same as Nothing, which indicates that a variable has not yet been initialized.

If row.Cells(0) IsNot Nothing Then ...

As before, you can test for Nothing, then for a specific value:

If (row.Cells(0) IsNot Nothing) AndAlso (IsDBNull(row.Cells(0).Value) = False) Then
Dim getFoo = (From f In dbContext.FooBars
               Where f.something = something
               Select f).FirstOrDefault

If Not IsDBNull(getFoo) Then
    If IsDBNull(getFoo.user_id) Then
        txtFirst.Text = getFoo.first_name
    Else
       ...

FirstOrDefault returns the first item or the default value, which is Nothing for reference types and never DBNull:

If getFoo IsNot Nothing Then...
Dim chk As CheckBox

chk = CType(Me.Controls(chkName), CheckBox)
If chk.Checked Then
    Return chk
End If

If a CheckBox with chkName can't be found (or exists in a GroupBox), then chk will be Nothing and be attempting to reference any property will result in an exception.

If (chk IsNot Nothing) AndAlso (chk.Checked) Then ...
dgvBooks.DataSource = loan.Books
dgvBooks.Columns("ISBN").Visible = True       ' NullReferenceException
dgvBooks.Columns("Title").DefaultCellStyle.Format = "C"
dgvBooks.Columns("Author").DefaultCellStyle.Format = "C"
dgvBooks.Columns("Price").DefaultCellStyle.Format = "C"

If dgvBooks has AutoGenerateColumns = True, it will create the columns, but it does not name them, so the above code fails when it references them by name.

Name the columns manually, or reference by index:

dgvBooks.Columns(0).Visible = True
xlWorkSheet = xlWorkBook.Sheets("sheet1")

For i = 0 To myDGV.RowCount - 1
    For j = 0 To myDGV.ColumnCount - 1
        For k As Integer = 1 To myDGV.Columns.Count
            xlWorkSheet.Cells(1, k) = myDGV.Columns(k - 1).HeaderText
            xlWorkSheet.Cells(i + 2, j + 1) = myDGV(j, i).Value.ToString()
        Next
    Next
Next

When your DataGridView has AllowUserToAddRows as True (the default), the Cells in the blank/new row at the bottom will all contain Nothing. Most attempts to use the contents (for example, ToString) will result in an NRE.

Use a For/Each loop and test the IsNewRow property to determine if it is that last row. This works whether AllowUserToAddRows is true or not:

For Each r As DataGridViewRow in myDGV.Rows
    If r.IsNewRow = False Then
         ' ok to use this row

If you do use a For n loop, modify the row count or use Exit For when IsNewRow is true.

Under certain circumstances, trying to use an item from My.Settings which is a StringCollection can result in a NullReference the first time you use it. The solution is the same, but not as obvious. Consider:

My.Settings.FooBars.Add("ziggy")         ' foobars is a string collection

Since VB is managing Settings for you, it is reasonable to expect it to initialize the collection. It will, but only if you have previously added an initial entry to the collection (in the Settings editor). Since the collection is (apparently) initialized when an item is added, it remains Nothing when there are no items in the Settings editor to add.

Initialize the settings collection in the form's Load event handler, if/when needed:

If My.Settings.FooBars Is Nothing Then
    My.Settings.FooBars = New System.Collections.Specialized.StringCollection
End If

Typically, the Settings collection will only need to be initialized the first time the application runs. An alternate remedy is to add an initial value to your collection in Project -> Settings | FooBars, save the project, then remove the fake value.

You probably forgot the New operator.

Something you assumed would perform flawlessly to return an initialized object to your code, did not.

Don't ignore compiler warnings (ever) and use Option Strict On (always).

c# - What is a NullReferenceException, and how do I fix it? - Stack Ov...

c# .net vb.net null nullreferenceexception