I have a dataTable with 5 rows and 2 columns(Id,Name). I need to pass only one column of the dataTable to a function parameter which is a dataTable.
This is what I tried
myfunction(dt.Rows.Item("Id")
Public function myfunction (dt as dataTable)
// Some code
End Function
But this is not working. Why is it so? Even if a column is excluded the dataTable still remains as a dataTable. How can I pass the "ID" column without including the "Name" column to this function as a parameter.
CodePudding user response:
There are several issues with what you provided.
First, your function call is missing a parentheses on the end.
myfunction(dt.Rows.Item("Id"))
Second, your function is expecting a datatable, but you are passing a cell (and also not specifying which row, so this wouldn't work)...
If you truly want your function to use a datatable, you need to just pass dt like:
myFunction(dt)
If you want to pass the cell value instead, you can change your function definition to take a string or whatever datatype is within that column, and pass the value like:
myFunction(dt.Rows(ROWNUMBER).Item("Id"))
CodePudding user response:
Functions need a DataType
and a Return
statement.
Your Function is expecting a DataTable
and you are passing a DataRow
.
dt.Rows.Item
takes a Integer
, not a String
.
You don't Dim
a Function
, you call it.
Stack Overflow asks for a Minimum, Complete and Reproducible example of your problem. Your code is not that.
I gave your Function a name and something trivial to do so I could demonstrate the proper syntax. If you don't need the whole DataTable then don't pass it to the function. I am just passing the values in the ID column as a List(Of T) If your Function is not under your control and it wants a DataTable, then just pass dt.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lst = dt.Rows.OfType(Of DataRow)().Select(Function(dr) dr.Field(Of Integer)("ID")).ToList()
Dim MaxID = GetMaxID(lst)
End Sub
Public Function GetMaxID(lst As List(Of Integer)) As Integer
Dim MaxI = lst.Max
Return MaxI
End Function