StephenT
StephenT

Reputation: 495

Add values to listbox from dataset - NullReferenceException error (VB.NET)

I'm trying to populate a single record from a dataset into a listbox. I can see that the dataset is populated with the expected value with the column header "PLI" in the dataset visualizer. I've tried to use the following command to populate the listbox with the value in the dataset:

lstExistingPLI.Items.Add(New ListItem(ds.Tables("PLI").ToString()))

I keep getting an unhandled NullReferenceException error. I've also tried using

lstExistingPLI.Items.Add(ds.Tables("PLI").ToString())

and getting the same error. Can anyone help me out with what I'm doing wrong? Thanks!

Upvotes: 0

Views: 5689

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460208

First i must admit that i don't know what causes your NullRefernceException.

Your ListBox lstExistingPLI might be null if you haven't initialized it. The DataSet ds might be null if it was not initialized. Maybe you have initialized it but you haven't added a DataTable with name "PLI" to it, then null would be returned from the DataTableCollection.Item property.

However, ds.Tables returns a DataTable. Why do you think that DataTable.ToString returns anything that could be added to a ListBox in a useful way? Do you want to add the fields of every DataRow?

(assuming that all is initialized correctly)

For Each  row As DataRow In ds.Tables(0).Rows
    'assuming that PLI is not the table but the field that you want to add to the ListBox'
    lstExistingPLI.Items.Add(New ListItem(row.Field(Of String)("PLI")))
Next

Upvotes: 1

Related Questions