linq on datarow to get index of specific item - linq

I have datatable which it first row is headers
I need specific column for this datatable according to the header
I know how to get the column if know its index.
The problem is how to get the index
Dim columnIndex as integer
Dim headerRow As DataRow = dt.Rows(0)
Dim colHeader As string ="abc"
columnIndex=???
Dim result = dt.Rows.Cast(Of DataRow)().[Select](Function(row) row(columnIndex)).Distinct().ToList()
Thanks

You may use the dt.Rows.IndexOf
Dim ValueToSearch AS string = ...
columnIndex = dt.AsEnumerable().Where(Function(x) x.Field(of String)(colHeader) = ValueToSearch).Select(Function(x) dt.Rows.IndexOf(x)).SingleOrDefault()
The above will work if the where clause returns only one or zero rows. If this is not true then you may dismiss the SingleOrDefault and then loop through the results, ie:
columnIndex = dt.AsEnumerable().Where(Function(x) x.Field(of String)(colHeader) = ValueToSearch).Select(Function(x) dt.Rows.IndexOf(x))
For Each i in columnIndex
Console.WriteLine("Value found in row with index " + i.ToString())
Next
Giannis

Related

How do you add your queried datatable results into a new datatable

Can someone please help me fill my queried results into the existing datatable or a new datatable
''dt is filled with data from a csv file.
Dim dataRows As DataRow() = dt.Select("[Calendar year TEXT] = '2020'")
dt.Clear() 'Clear the datatable
dt.Rows.Add(dataRows) 'Add the result to the existing datatable or a new databletable if possible ?
So I've figured it out.
The reason I need a new DataTable is that I need to use it again in its original form later.
I could not attach the DataRow collection to my display control which is why I needed a new DataTable with the filtered results.
Private Function FilterDataTable(ByVal strQuery As String, ByVal dtRaw As DataTable)
Dim dataRows As DataRow() = dtRaw.Select(strQuery)
Dim dtFiltered As DataTable
dtFiltered = dtRaw.Clone() 'This is very important.
For Each drow As DataRow In dataRows
dtFiltered.ImportRow(drow) 'Add each filtered row to new DataTable.
Next
Return dtFiltered
End Function
Your dt.select will return an array of Datarow pointing to the rows in the datatable dt. Your dt.clear then clears the datatable and so will empty the dataRows array leaving you nothing left.
I'm not clear exactly what you are trying to do. I'm guessing you have a table that you want to filter and then discard all rows that don't match, leaving you a datatable to work with.
If so, here's a few options:
Work with the datarow array directly rather than the datatable. Is there really any need to convert the rows back to a datatable?
Create a new datatable to add the rows to, but don't clear the original table:
Dim dt As New DataTable ' Assume this is your populated table
Dim dataRows As DataRow() = dt.Select("[Calendar year TEXT] = '2020'")
Dim dtResults As DataTable = dt.Clone()
For Each row As DataRow In dr
dtResults.ImportRow(row)
Next
bare in mind any changes you make to the rows in dtResults will also affect the rows in dt as they both contain the same data
Depending on the size of your table and whether or not you really want to discard non matching rows, you could just remove all rows that don't match then work with the result:
Dim i As Integer = dt.Rows.Count - 1
While i >= 0
If dt(i).Item("Calendar") <> "Your test here" Then dt.Rows.Remove(dt(i))
i -= 1
End While

How do i set the celltype for a datagrid column?

I am adding a new column to a datagrid to store a row total of qty*Cost
When I try to add the column I get an exception saying
System.InvalidOperationException: 'Column cannot be added because its CellType property is null.'
I've tried to set the cell type but I can't get the type right
Dim dt As DataTable = Me.DsOppQuoteDetail.tblOppQuoteDetail
Dim dr As DataRow
Dim dc As New DataGridViewColumn
With dc
.HeaderText = "Item Total"
.Name = "UnitTotal"
.CellType = DataGridTextBox
End With
DGV_OppQuoteDetail.Columns.Insert(6, dc)
Setting the CellType to DataGridTextBox produces an error
If I change the the column to:
Dim dc As New DataGridTextBoxColumn
With dc
.HeaderText = "Item Total"
End With
DGV_OppQuoteDetail.Columns.Insert(6, dc)
then I can't insert it because it's the wrong type for the DataGrid.Insert command
Dim dc As New DataGridViewTextBoxColumn
dc.HeaderText = "SomeText"
dc.Name = "colWhateverName"
DGV_OppQuoteDetail.Columns.Add(dc)
Try this and let me know. Only slightly different in terms of wording. Also from your code snippet it seems fine but make sure you don't add any rows before adding a column.

DataTable: create rows dynamically according to the number of checkboxes selected in the checkbox List

I am trying to create a DataTable the number of rows of which needs to be created automatically according to the number of checkboxes checked in my checkbox list:
Private Function GetRoomTypeIds() As DataTable
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Id", GetType(Integer)), New DataColumn("RoomTypeId", GetType(Integer))})
dt.Rows.Add(txtId1.Text, chkRoomTypes.SelectedValue)
Return dt
End Function
I would need to add something like:
"For Each Checkbox checked in my checkbox list generate the corresponding number of rows."
Thanks
I solved as per below code:
Private Function GetRoomTypeIds() As DataTable
Dim selectedItems = From s In chkRoomTypes.Items.Cast(Of ListItem)
Where s.Selected
Select s
Dim itemTable As DataTable
itemTable = New DataTable("SelectedItems")
Dim column1 As DataColumn = New DataColumn("RateTypeId")
column1.DataType = System.Type.GetType("System.Int32")
Dim column2 As DataColumn = New DataColumn("RoomTypeId")
column2.DataType = System.Type.GetType("System.Int32")
itemTable.Columns.Add(column1)
itemTable.Columns.Add(column2)
Dim Row As DataRow
For Each item In selectedItems
Row = itemTable.NewRow()
Row("RateTypeId") = Convert.ToInt32(txtId1.Text)
Row("RoomTypeId") = item.Value
itemTable.Rows.Add(Row)
Next
Return itemTable
End Function
Thanks

Filter generic list (comma separated values)

I want to filter list as below. I have a class & I want to filter values from that are in my filter string. I have achieved my result by a for loop but need a way without for loop.
Public Class WorkStationDetails<br><br>
Property CountryId As Integer<br>
Property CountryName As String<br>
Property TotalWrkStn As Integer<br>
Property ExistingWrkStn As Integer<br>
Property RemainingWrkStn As Integer<br><br>
End Class
Dim WrkStnDtl As List(Of WorkStationDetails)
Dim FilterWrkStnDtl As List(Of WorkStationDetails)
Dim Numbers As String()
Numbers = "1,5,6,2,9".Split(",")
For i As Integer = 0 To Numbers.Length - 1
FilterWrkStnDtl.AddRange(WrkStnDtl.FindAll(Function(p) (p.CountryId = Numbers(i))))
Next
Note: I want to achieve it like subquery in sql server.
I think you want something like this"
var numbers = "1,5,6,2,9".Split(',');
var selected = WrkStnDtl.Where(w => numbers.Contains(w.CountryId)).ToList();

How to find if dataGrid contains a column

Given an existing DataGrid called grid.
When I try to access grid.Columns("column_name") I get an exception
Column not found, column_name
I tried
If Not IsNull(grid.Columns("column_name")) Then '...
but I still get the exception.
I would like something which I could call like
grid.ContainsColumn("column_name")
The columns in a DataGrid only have a caption text to identify what the column is so you could use something like this to check if the column exists by looking for a column with a Caption that matches the column name you are looking for.
Private Function DataGrid_CheckColumnExists(dataGrid As dataGrid, columnName As String)
Dim columnCount As Long, columnIndex As Long
Dim checkColumnName As String
columnCount = dataGrid.Columns.Count
For columnIndex = 0 To columnCount - 1
checkColumnName = dataGrid.Columns(columnIndex).Caption
DataGrid_CheckColumnExists = (StrComp(checkColumnName, columnName, vbTextCompare) = 0)
If DataGrid_CheckColumnExists Then Exit Function 'No need to continue once we found it
Next columnIndex
End Function

Resources