Converting Gridview to DataTable in VB.NET - vb.net

I am using this function to create datatable from gridviews. It works fine with Gridviews with AutoGenerateColumns = False and have boundfields or template fileds. But if I use it with Gridviews with AutoGenerateColumn = True I only get back an empty DataTable. Seems Gridview viewstate has been lost or something. Gridview is binded on PageLoad with If Not IsPostback. I can't think of anything else to make it work. Hope someone can help me.
Thanks,
Public Shared Function GridviewToDataTable(gv As GridView) As DataTable
Dim dt As New DataTable
For Each col As DataControlField In gv.Columns
dt.Columns.Add(col.HeaderText)
Next
For Each row As GridViewRow In gv.Rows
Dim nrow As DataRow = dt.NewRow
Dim z As Integer = 0
For Each col As DataControlField In gv.Columns
nrow(z) = row.Cells(z).Text.Replace(" ", "")
z += 1
Next
dt.Rows.Add(nrow)
Next
Return dt
End Function

Slight modification to your function above. If the autogenerate delete, edit or select button flags are set, the values for the fields are offset by one. The following code accounts for that:
Public Shared Function GridviewToDataTable(ByVal PassedGridView As GridView, ByRef Error_Message As String) As DataTable
'-----------------------------------------------
'Dim Tbl_StackSheets = New Data.DataTable
'Tbl_StackSheets = ReportsCommonClass.GridviewToDataTable(StackSheetsGridView)
'-----------------------------------------------
Dim dt As New DataTable
Dim ColInd As Integer = 0
Dim ValOffset As Integer
Try
For Each col As DataControlField In PassedGridView.Columns
dt.Columns.Add(col.HeaderText)
Next
If (PassedGridView.AutoGenerateDeleteButton Or PassedGridView.AutoGenerateEditButton Or PassedGridView.AutoGenerateSelectButton) Then
ValOffset = 1
Else
ValOffset = 0
End If
For Each row As GridViewRow In PassedGridView.Rows
Dim NewDataRow As DataRow = dt.NewRow
ColInd = 0
For Each col As DataControlField In PassedGridView.Columns
NewDataRow(ColInd) = row.Cells(ColInd + ValOffset).Text.Replace(" ", "")
ColInd += 1
Next
dt.Rows.Add(NewDataRow)
Next
Error_Message = Nothing
Catch ex As Exception
Error_Message = "GridviewToDataTable: " & ex.Message
End Try
Return dt
End Function

Related

value of type integer cannot be converted to datatable vn.net

i am trying to create tree view and some error i can not fix it
Sub CREATENODE()
Dim TRN As New TreeNode
Dim DT As New DataTable
DT.Clear()
DT = ACCOUNTTableAdapter.TREE_ACCOUNT()
For I As Integer = 0 To DT.Rows.Count - 1
If DT.Rows(I)(9).ToString() = "00000000-0000-0000-0000-000000000000" Then
TRN = New TreeNode(DT.Rows(I)(3).ToString() + " " + DT.Rows(I)(4).ToString())
TRN.Tag = DT.Rows(I)(1).ToString()
If DT.Rows(I)(7).ToString() <> "0" Then
TRN.ImageIndex = 0
TRN.SelectedImageIndex = 0
Else
TRN.ImageIndex = 1
TRN.SelectedImageIndex = 1
End If
TreeView1.Nodes.Add(TRN)
End If
Next
''For Each NODE As TreeNode In TreeView1.Nodes
'' CHELD(NODE)
'Next
End Sub
This is nonsense
Dim TRN As New TreeNode
Dim DT As New DataTable
DT.Clear()
DT = ACCOUNTTableAdapter.TREE_ACCOUNT()
You create a New TreeNode and then inside the loop you overwrite it with another New one. Just put the Dim inside the loop after the if.
Dim TRN = New TreeNode($"{row(3)} {row(4)}")
You create a brand new DataTable. Then you clear it when it can't possibly have anything in it. Then you throw it away and assign a different DataTable to it.
Just do
Dim DT = ACCOUNTTableAdapter.TREE_ACCOUNT()
I have simplified your code by using a For Each loop. Also, I used and interpolated string indicated by the $ preceding the string. Variables can be inserted in place surrounded by braces { }.
As far as the actual problem, you need to create an instance of your table adapter with the New keyword. Then call the appropriate method. A simple application will just use .GetData.
Private Sub CREATENODE()
Dim DT = (New ACCOUNTTableAdapter).TREE_ACCOUNT() 'See what intellisense offers. It may be just .GetData
For Each row As DataRow In DT.Rows
If row(9).ToString() = "00000000-0000-0000-0000-000000000000" Then
Dim TRN = New TreeNode($"{row(3)} {row(4)}")
TRN.Tag = row(1)
If row(7).ToString() <> "0" Then
TRN.ImageIndex = 0
TRN.SelectedImageIndex = 0
Else
TRN.ImageIndex = 1
TRN.SelectedImageIndex = 1
End If
TreeView1.Nodes.Add(TRN)
End If
Next
End Sub
Hint: Why not put the entire row in the Tag property. You will have access to all the fields by casting the Tag back to a DataRow.

Empty lines appears in datagridview

When I go to add data in first row there is empty lines that appear below my code, why do these lines appear? I need only to add data in one row and save it.
Dim pringdata As String = "SELECT * FROM itemInfo "
Dim sqlconload As New SqlConnection(sqlcon)
Try
sqlconload.Open()
Dim da As New SqlDataAdapter(pringdata, sqlconload)
ds.Clear()
da.Fill(ds, "itemInfo")
Dim rowcount As Integer
rowcount = ds.Tables("itemInfo").Rows.Count
If rowcount >= 1 Then
DGVorders.Rows.Add(rowcount)
For i = 0 To rowcount - 1
If DGVorders.CurrentRow.Cells(0).Value = ds.Tables("itemInfo").Rows(i).Item("itemCode") Then
DGVorders(1, e.RowIndex).Value = ds.Tables("itemInfo").Rows(i).Item("itemName")
DGVorders(2, e.RowIndex).Value = ds.Tables("itemInfo").Rows(i).Item("Uint1")
DGVorders(4, e.RowIndex).Value = ds.Tables("itemInfo").Rows(i).Item("price1")
End If
Next
End If
sqlconload.Close()
Catch ex As Exception
End Try
End Sub
Modify the "AllowUsersToAddRows" property to remove that blank line.
Example:
DataGridView1.AllowUserToAddRows = False
DGVorders.Rows.Add(rowcount) will add rowcount amount of empty rows to your DataGridView. I don't know why you are doing that, it's not as if you are adding values to the cells in those new rows in your for loop.
updated
If dataGridView1.CurrentRow.Cells(0).Value = ds.Tables("itemInfo").Rows(i)("itemCode") Then
Dim newRow As DataGridViewRow = TryCast(dataGridView1.CurrentRow.Clone(), DataGridViewRow)
newRow.Cells(1).Value = ds.Tables("itemInfo").Rows(i)("itemName")
newRow.Cells(2).Value = ds.Tables("itemInfo").Rows(i)("Uint1")
newRow.Cells(3).Value = ds.Tables("itemInfo").Rows(i)("price1")
dataGridView1.Rows.Add(newRow)
End If

Trimming a datagridview duplicat rows except the recent one

i'm in VS2008 Studio, i have this datagridview with multiple columns which the last column contains a date and time value.
lot's of rows are pretty the same except by they're date column.
what i wanted to do is to trim the whole datagridview duplicate rows except they're most recent ones based on they're date column.
i have sth like this:
Administrator,192.168.137.221,2,file://C:\WMPub\WMRoot\industrial.wmv , 07.Jul.2014 - 23:11:59
Administrator,192.168.137.221,2,file://C:\WMPub\WMRoot\industrial.wmv , 07.Jul.2014 -
21:11:59
Administrator,192.168.137.221,2,file://C:\WMPub\WMRoot\industrial.wmv , 07.Jul.2014 - 22:11:59
Administrator,192.168.137.221,2,file://C:\WMPub\WMRoot\industrial.wmv , 07.Jul.2014 - 20:11:59
Administrator,192.168.137.221,2,file://C:\WMPub\WMRoot\industrial.wmv , 07.Jul.2014 - 11:11:59
Everyone ,192.168.137.221,2,file://C:\WMPub\WMRoot\industrial.wmv , 07.Jul.2014 - 17:11:59
Everyone ,192.168.137.221,2,file://C:\WMPub\WMRoot\industrial.wmv , 07.Jul.2014 - 14:11:59
the output i want should be like this:
Administrator 192.168.137.221 2 file://C:\WMPub\WMRoot\industrial.wmv 07.Jul.2014 - 23:11:59
Everyone 192.168.137.201 2 file://C:\WMPub\WMRoot\industrial.wmv 07.Jul.2014 - 17:11:59
....
please consider "," as column seprators! (i dont know how to draw a table here, sorry again)!
i have this snippet that trim the duplicate lines in a datagridview but it lacks preserving the latest entry:
Public Function RemoveDuplicateRows(ByVal dTable As DataTable, ByVal colName As String) As DataTable
Dim hTable As New Hashtable()
Dim duplicateList As New ArrayList()
For Each dtRow As DataRow In dTable.Rows
If hTable.Contains(dtRow(colName)) Then
duplicateList.Add(dtRow)
Else
hTable.Add(dtRow(colName), String.Empty)
End If
Next
For Each dtRow As DataRow In duplicateList
dTable.Rows.Remove(dtRow)
Next
Return dTable
End Function
what should i do?
thanks in advance
Here is some code that illustrates the approach:
Dim dict As New dictionary(Of String, DataRow)
For Each dtRow As DataRow In dTable.Rows
Dim key As String = dtRow("column1") + "," + dtRow("column2") ' + etc.
Dim dictRow As DataRow = Nothing
If dict.TryGetValue(key, dictRow) Then
'check and update date
'you can skip this part, if your data is sorted
If dtRow("dateColumn") > dictRow("dateColumn") Then
dictRow("dateColumn") = dtRow("dateColumn")
End If
Else
dict.Add(key, dtRow)
End If
Next
In the end dict contains the rows you need, you can get them via dict.Values.ToArray()
EDIT: I found the error - dictRow should be dtRow in the above code (now fixed). Then it should work. Here is a full version of self contained example (console app), since I wrote it anyway - focus on RemoveDuplicates, the rest is just prepwork:
Sub Main()
Dim dt As New DataTable
With dt.Columns
.Add("PublishingPoint")
.Add("Username")
.Add("IP")
.Add("Status")
.Add("Req URL")
.Add("Last seen", GetType(Date))
End With
'this populates the initial data table, use your method
Dim _assembly As Assembly = Assembly.GetExecutingAssembly()
Dim _textStreamReader As New StreamReader(_assembly.GetManifestResourceStream("ConsoleApplication16.data.csv"))
While Not _textStreamReader.EndOfStream
Dim sLine As String = _textStreamReader.ReadLine().TrimEnd
If String.IsNullOrEmpty(sLine) Then Exit While
Dim values() As String = sLine.Split(",")
Dim newRow As DataRow = dt.NewRow
For iColumnIndex As Integer = 0 To dt.Columns.Count - 1
Dim columnName As String = dt.Columns(iColumnIndex).ColumnName
newRow.Item(columnName) = values(iColumnIndex)
Next
dt.Rows.Add(newRow)
End While
Console.WriteLine("Old count: " & dt.Rows.Count)
Dim newDt As DataTable = RemoveDuplicates(dt, "Last seen")
Console.WriteLine("New count: " & newDt.Rows.Count)
Console.ReadLine()
End Sub
Private Function RemoveDuplicates(dt As DataTable, colName As String) As DataTable
Dim keyColumnNames As New List(Of String)
Dim exceptColumnsHash As New HashSet(Of String)({colName})
For Each col As DataColumn In dt.Columns
Dim columnName As String = col.ColumnName
If Not exceptColumnsHash.Contains(col.ColumnName) Then
keyColumnNames.Add(columnName)
End If
Next
Dim dict As New Dictionary(Of String, DataRow)
For Each dtRow As DataRow In dt.Rows
Dim keyColumnValues As New List(Of String)
For Each keyColumnName In keyColumnNames
keyColumnValues.Add(dtRow.Item(keyColumnName))
Next
Dim key As String = String.Join(",", keyColumnValues)
Dim dictRow As DataRow = Nothing
If dict.TryGetValue(key, dictRow) Then
If dtRow(colName) > dictRow(colName) Then
dictRow(colName) = dtRow(colName)
End If
Else
dict.Add(key, dtRow)
End If
Next
Dim dtReturn As DataTable = dt.Clone
For Each dtRow As DataRow In dict.Values
dtReturn.ImportRow(dtRow)
Next
Return dtReturn
End Function
To make this code run, you need to manually add a file to the project and set build action to "Embedded resource".

Getting Info out of a DataGridView

I need to get the information that is in each cell located in the datagrid view of the rows that the user selects. I have the selecting rows down, I just need help with getting the information in the cell. Right now it just returns as DataGridVewRow { Index=7} when the data is really a string. Here is my function
Private Function getCoordinates()
Dim dt As New DataTable
Dim dt2 As New DataTable
'Dim r As DataRow
Dim n As Integer = 0
Dim selectedItems As DataGridViewSelectedRowCollection = dgv.SelectedRows
dt = dgv.DataSource
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
dgv.MultiSelect = True
Dim i = dgv.CurrentRow.Index
dt2.Columns.Add("Position")
Try
If selectedItems Is Nothing Then
For n = 0 To dt.Rows.Count - 1
dt2.Rows.Add(n)
dt2.Rows(n)("Position") = dt.Rows.Item(n)("Mouse Position")
Next
Else
For Each selectedItem As DataGridViewRow In selectedItems
dt2.Rows.Add(selectedItem)
dt2.Rows(selectedItem.Index)("Position") = dt.Rows.Item(selectedItem.Index)("Mouse Position")
Next
End If
Catch ex As Exception
MsgBox("Error", MsgBoxStyle.Exclamation, "Error!")
End Try
Return dt2
End Function
You get the text of the cells via the DataGridViewRow's Cells property. The following example would get the text from the first cell in each selected row:
Dim strContents As String = String.Empty
For Each selectedItem As DataGridViewRow In selectedItems
strContents += " First Cell's Text: " & selectedItem.Cells(0).Text
Next

DataGridView Multiple Row Selection Issue

I am trying to check for multiple selections in a DataGridView with a For... Next Loop, but even though I have selected multiple rows, the only row with the property Selected=True is the first row in the selection. Is there a way around this?
MultiSelect is true on the DataGridView.
My code is as follows:
For Each dr As DataGridViewRow In dgv.Rows
If dr.Selected = True Then
intSelectedRow = dr.Index
SetTime("KeyEntry", dgv.Name, intSelectedRow)
End If
Next
Thanks
Try this:
Dim selectedItems As DataGridViewSelectedRowCollection = dgv.SelectedRows
For Each selectedItem As DataGridViewRow In selectedItems
'Add code to handle whatever you want for each row
Next
End Sub
Dim Message As String = String.Empty
Dim FNL As FinalRpt = New FinalRpt()
For Each ItemRow As DataGridViewRow In DGVItems.Rows
Dim ISSelected As Boolean = Convert.ToBoolean(ItemRow.Cells("MyChkBox").Value)
If ISSelected Then
Message &= Environment.NewLine
Message &= ItemRow.Cells("I_ID").Value.ToString()
Dim SelectedRow As Integer = DGVItems.Rows.GetRowCount(DataGridViewElementStates.Selected)
Dim RPTItemsDA As OleDbDataAdapter
Dim RPTItemsDS As DataSet
Dim I As Integer
For I = 0 To SelectedRow Step 1
RPTItemsDA = New OleDbDataAdapter("Select Distinct * From stkrpt Where I_ID = " & DGVItems.SelectedRows(I).Index.ToString() & "", DBConnect)
RPTItemsDS = New DataSet
RPTItemsDA.Fill(RPTItemsDS, "stkrpt")
FNL.DGVReport.DataSource = RPTItemsDS
FNL.DGVReport.DataMember = "stkrpt"
Next
FNL.MdiParent = MDIParent1
FNL.StartPosition = FormStartPosition.CenterScreen
FNL.WindowState = FormWindowState.Maximized
Me.Hide()
FNL.Show()
ISSelected = False
End If
Next
MessageBox.Show(Message)