Re: Updating a datarow by RobinS
RobinS
Tue Mar 11 22:31:31 CDT 2008
"John Terry" <jt26@chelseafc.com> wrote in message
news:ebHEfhugIHA.5900@TK2MSFTNGP02.phx.gbl...
>I am having a problem putting all of the pieces together on this one and
>would appreciate some help.
>
> I need to find a row based on certain criteria, retrieve its Item Number
> or position in the table, then update a field in the row.
>
> In other words, locate the row where Field1 = x, update Field2 =y
>
> I see examples of how to find a row using Select and I know how to update
> if I know the Item number, but I can't put everything together.
>
>
> Thanks in advance...
>
Here's an example. dt is a DataTable, this does a find based on a one-field
primary key, looking for a row where the value = "NEWCO". Note that the Find
method is overloaded.
Dim rw as DataRow = dt.Rows.Find("NEWCO")
If rw Is Nothing Then
'Customer not found
Else
'It found the customer, set the name to a new value
rw("CustomerName") = "New Value"
End If
Here's an example of searching for a multiple-column primary key:
dt.PrimaryKey = New DataColumn() {dt.Columns("OrderID"),
dt.Columns("ProductID")}
Dim objCriteria As New Object() {10643, 28}
Dim row As DataRow = dt.Rows.Find(objCriteria)
Here's another example using a DataView:
Once you've set the Sort property on a DataView object, you can call its
Find method to locate a row based on the columns specified in the Sort
property. Can specify single value or array of values.
This returns an integer value that corresponds to the index of the desired
row in the DataView. If can't find it, it returns -1.
Dim dv as New DataView(dt) 'dt is Customers table
dv.Sort = "ContactName"
Dim Index As Integer = dv.Find("Fran Wilson")
If Index = -1 Then
'not found
Else
Console.WriteLine(dv(Index)("CompanyName"))
End If
These examples are from Dave Sceppa's ADO.Net book. Check it out; it's a
great book.
Hope this helps.
RobinS.
GoldMail.com