Confused on something so basic ... arrays!

pachjo

Well-known member
Joined
Dec 12, 2006
Messages
370
Programming Experience
10+
I need to declare an object array to store a primary key to use with the .Find method of the datarowcollection.

My table has a single field primary key so I only need 1 entry in my object array.

VB.NET:
Dim a(1) as object

Then I assign the primary key

VB.NET:
a(0) = me.combo1.selecteditem

And then delete the item

VB.NET:
Me.MyDataSet.System.Rows.Find(a).Delete()

But a() contains two rows a(0) the selected item and a(1)=nothing.

I cannot see the wood for trees!!

How do I set a() to be an object array with only one entry?

Thnx
 
this is how the array should be. arrays are zero based.
i'm not sure about the find/delete.
if this doesn't work, try declaring a() as string

Dim a(0) as object
a(0) = me.combo1.selecteditem
Me.MyDataSet.System.Rows.Find(a(0)).Delete()

edit: why does it have to be an array anyway?
why not a variable?
 
What you're doing is unnecessary because the DataRowCollection.Find method is overloaded. The point of the Find method is that it takes a primary key value. If your table's primary key is simple, i.e. one column, then you should be passing just a single value. If your table's primary key is composite, i.e. multiple columns, then you should be passing an array containing the value for each column. Under no circumstances should you be passing an array with a single element. You should be doing this:
VB.NET:
Me.MyDataSet.System.Rows.Find(Me.ComboBox1.SelectedItem).Delete()
That said, when you create an array you must specify its upper bound. By doing this:
VB.NET:
Dim a(1) As Object
you are creating an array with an upper bound of 1, i.e. elements at indexes 0 and 1. If you wanted an array with one element then the upper bound will be zero:
VB.NET:
Dim a(0) As Object

a(0) = Me.ComboBox1.SelectedItem
That said, in that case it would be smarter to specify the upper bound implicitly:
VB.NET:
Dim a As Object() = {Me.ComboBox1.SelectedItem}
 
Doh! I know about zero base but did not know Dim a(0) was valid!!

However jmcilhinney thanks for a very concise explaination, problem resolved :)
 
this is how the array should be. arrays are zero based.
i'm not sure about the find/delete.
if this doesn't work, try declaring a() as string

Dim a(0) as object
a(0) = me.combo1.selecteditem
Me.MyDataSet.System.Rows.Find(a(0)).Delete()

edit: why does it have to be an array anyway?
why not a variable?

my knowledge of the .Find method was that to use it you had to use an object array as detailed in the object browser help. ;-)
 
You need to look a bit more carefully. As I said, Find is overloaded. The Object Browser lists both overloads, one with an Object argument and one with an Object array argument.
 
Back
Top