Вопрос

Good morning stackers!

I'm designing a massive update page. Here are the general steps:

  1. I have a class called item which has two properties: Equipment number and new due date.
  2. I have a textbox where i paste values from Excel, the values consist of two columns divided by a vbtab character: the columns are an equipment number and a new due date
  3. A button is clicked and the values from textbox are parsed into a list(of item) and the equipment master builds a string for an SQL criteria for a commandtext.
  4. The command fills a dataset from a database which gets equipment number and current due date.
  5. I add manually a column to the dataset (new due date)
  6. I iterate over the rows of the dataset, and i use the list(of item) find method matching equipment from the list and from the database to get a new due date from the textbox parsed values.
  7. Everything is going well, except that when using the find method for more than 1 row in the dataset, the method fails:

Here is the code from point 5 and 6:

da.Fill(ds, "Equipments")
dt = ds.Tables(0)
ds.Tables(0).Columns.Add("column_1", Type.GetType("System.DateTime"))
Dim rw As DataRow
For Each rw In ds.Tables(0).Rows
  Dim strsearch As String = rw(0).ToString
  Dim fequnumb As item = myItemList.Find(Function(p) p.EquipNumber = strsearch)
  rw(2) = fequnumb.DueDate <- Error occurs here
Next

Again, if instead of ftechid.DueDate I put a static value like Today()the code runs fine for the loop and fills correctly the gridview, but if i leave the ftechid.DueDate then an error is thrown after the first row:

Object reference not set to an instance of an object. 

Any help is very much appreciated as to how to use the find method inside a for..each loop

Это было полезно?

Решение

If the Find function cannot match the string requested it returns Nothing and then you cannot set the due date from a variable that is Nothing. If this is a condition expected from the input then you need to protect the assignment to the new column with something like this.

For Each rw In ds.Tables(0).Rows
  Dim strsearch As String = rw(0).ToString
  Dim fequnumb As item = myItemList.FirstOrDefault(Function(p) p.EquipNumber = strsearch)
  if fequnumb IsNot Nothing Then
     rw(2) = fequnumb.DueDate <- Error occurs here
  End if
Next

If this is not supposed to happen then you need to check your inputs

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top