John Nuñez
John Nuñez

Reputation: 1830

Find a Value in Two Dimensional Array on VB.NET

I declared my Array:

Dim invoice_discountitems(100, 100) As String

Set Values into array:

For i As Int16 = 0 To data_set.Tables("discount_items").Rows.Count - 1
    invoice_discountitems(i, 1) = data_set.Tables("discount_items").Rows(0).Item("item_code")
    invoice_discountitems(i, 2) = data_set.Tables("discount_items").Rows(0).Item("discountitem_average")
Next

Now I try to find a single value:

Dim res As String
res = Array.IndexOf(invoice_discountitems, "FO1506")
MsgBox(res)

But, I get this error :(

"Only single dimension arrays are supported here"

Upvotes: 0

Views: 15324

Answers (2)

Hadas
Hadas

Reputation: 10384

First of all IndexOf return int as index!

To get the index of string Try:

Dim i As int
Dim j As int
i = Array.IndexOf(invoice_discountitems.OfType(Of String)().ToArray(), "FO1506")
j = i MOD 100
i= i/100
MsgBox(i+" "+j)

(I use c# but I think it's not different)

Upvotes: 0

Basic
Basic

Reputation: 26766

This is a fundamentally wrong approach - for a number of reasons

  • You're treating ALL the data points as Strings
  • You're not taking advantage of DB optimisations like indices
  • You're loading data into memory that you're never going to use (at least int he example)

The Nicest way to do it would be with Linq-To-Entities:

Dim Record = MyDBContext.Discount_Items.Where(function(x) x.ItemCode = "FO1506").Single
Console.WriteLine(Record.discountitem_average);

If you're stuck with your current Data Access Layer, you need to modify the SQL being executed to only return the information you're interested in. Without more information, I can't provide decent example code but you want the SQL to end up looking like this...

SELECT  itemcode,
        discountitem_average,
        [Other fields],
FROM    MyDatabase.M

EDIT: To Clarify, there are a number of ways to access data in a database. The one I prefer is LINQ-To-Entities (Have a look through this tutorial).

In short, you add a new Item to your project and point it at your database. This becomes your "Database Context" - it represents the database and that's how you run queries.

Project -> Add -> New Item...

Select ADO.Net Entity Data Model (Linq-To-Entities is almost Identical to Linq-To-Sql but more recent and better supported - use Entities until you know the difference)

Call it something like MyDBContext

When prompted, choose "Generate From Database" and point it at your database.

It's worth noting that the designer takes advantage of information in the database like Foreign Key Constraints - So the better your database is designed, the better the model it will create.

Then, you refer to it in code as shown in my first example.

Upvotes: 1

Related Questions