Below is a loop I am trying to use to get the values from a GridViewRow into a DataRow object (using the godforsaken language of Visual Basic). However, on this line:
dr(i) = r.Cells(i).Text
I keep getting the following error message:
the value of type string cannot be converted to system.data.datarow
Can someone point me in the right direction on how to do this?
Dim rows As New List(Of GridViewRow)()
For Each item As GridViewRow In grdExpProd.Rows
rows.Add(item)
Next
Dim value As Integer = rows.Count
Dim dt As New DataTable()
For index As Integer = value - 1 To 0 Step -1
Dim dr As DataRow()
Dim r As GridViewRow = rows(index)
For i As Integer = 0 To r.Cells.Count - 1
dr(i) = r.Cells(i).Text
Next
dt.Rows.Add(dr)
Next
I believe you need to be adding your text to the DataRows Item Property which will allow you access to the individual cells of the DataRow. You are also going to need to add the columns that exist in your GridRowView to your new DataTable.
For i = 1 To rows(0).Cells.Count
dt.Columns.Add("Header" & i)
Next
For index As Integer = value - 1 To 0 Step -1
Dim dr As DataRow = dt.NewRow()
Dim r As GridViewRow = rows(index)
For i As Integer = 0 To r.Cells.Count
dr.Item(i) = r.Cells(i).Text
Next
dt.Rows.Add(dr)
Next
You accidentally created dr as an array of DataRow objects, not as a single DataRow object. Try replacing
Dim dr As DataRow()
with
Dim dr As New DataRow()
Try replacing
Dim dr As DataRow()
with
Dim dr As DataRow = dt.NewRow()
Also, as another poster pointed out, you need to create columns in your data table before attempting to add rows to it.
Related
I retrieved list of suppliers from database and saved it in an array TOTAL_SUPPLIERS_ARRAY NOW i am trying it to add in the listbox or combobox but it shows an error on runtime saying "VALUE CAN NOT BE NULL" but if i try to add it with an loop it works properly why is it not working with .addrange ?
Sub GET_SUPPLIERS_DETAILS()
Dim CON As New MySqlConnection("server=localhost; username=root; password=Masoom1; database=airtech_db;")
Dim cmd As New MySqlCommand("Select * from `Suppliers`;", CON)
Dim da As New MySqlDataAdapter("Select * from `Suppliers`;", CON)
Dim ds As New DataSet
Dim dr As MySqlDataReader
Dim TOTAL_SUPPLIERS As Integer
CON.Open()
da.Fill(ds)
dr = cmd.ExecuteReader
TOTAL_SUPPLIERS = ds.Tables(0).Rows.Count
Dim TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS) As String, ARRAYINDEX As Integer
Do While dr.Read() = True
TOTAL_SUPPLIERS_ARRAY(ARRAYINDEX) = dr("Supplier_Name").ToString()
ARRAYINDEX += 1
Loop
CON.Close()
Dim cbCell As New DataGridViewComboBoxCell
For k = 0 To DataGridView1.Rows.Count - 1
cbCell = DataGridView1.Rows(k).Cells("Supplier_Name")
For iIndex = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
cbCell.Items.Add(TOTAL_SUPPLIERS_ARRAY(iIndex))
Next
Next
ListBox1.Items.AddRange(TOTAL_SUPPLIERS_ARRAY)
ComboBox1.Items.AddRange(TOTAL_SUPPLIERS_ARRAY)
For I As Integer = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
TextBox1.Text += TOTAL_SUPPLIERS_ARRAY(I) & " - "
Next I
End Sub
This part works only as i added it through a loop
For I As Integer = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
TextBox1.Text += TOTAL_SUPPLIERS_ARRAY(I) & " - "
Next I
listbox.addrange command and combobox.addrange command not working
Here you have an issue TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS). Array declared in VB - array(upper-bound). Upper bound is 1 less than count. So, you should do TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS - 1).
But why struggle? Just use list
Dim myList as New List(of String)
While dr.Read()
myList.Add(dr("Supplier_Name").ToString())
Loop
And then, if you still need array, you can use LINQ - myList.ToArray
ListBox1.DataSource = myList.ToArray()
I need your help for my code vb
In fact, i created an new datatable and i want to copy the headers from another datatable
here is my code
Dim name(de.Tables(0).Columns.Count) As String
Dim p As Integer = 0
For Each column As DataColumn In de.Tables(0).Columns
name(p) = column.ColumnName
p += 1
Next
Dim m As Integer = 0
For m = 0 To de.Tables(0).Columns.Count - 1
dt.Columns(m).ColumnName = name(p)
Next
If you only want to "copy" the schema of a DataTable(so the columns and constraints) without it's content(DataRows) you can use DataTable.Clone:
Dim clonedTable As DataTable = originalTable.Clone()
If you also want to copy the DataRows you have to use DataTable.Copy.
Try this one
Dim dt As New DataTable()
Dim name(de.Tables(0).Columns.Count) As String
For Each column As DataColumn In de.Tables(0).Columns
dt.Columns.Add(New DataColumn(column.ColumnName))
Next
So, quite simple.
I am importing CSVs into a datagrid, though the csv always has to have a variable amount of columns.
For 3 Columns, I use this code:
Dim sr As New IO.StreamReader("E:\test.txt")
Dim dt As New DataTable
Dim newline() As String = sr.ReadLine.Split(";"c)
dt.Columns.AddRange({New DataColumn(newline(0)), _
New DataColumn(newline(1)), _
New DataColumn(newline(2))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(";"c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1), newline(2)}
dt.Rows.Add(newrow)
End While
DG1.DataSource = dt
This works perfectly. But how do I count the number of "newline"s ?
Can I issue a count on the number of newlines somehow? Any other example code doesn't issue column heads.
If my csv file has 5 columns, I would need an Addrange of 5 instead of 3 and so on..
Thanks in advance
Dim sr As New IO.StreamReader(path)
Dim dt As New DataTable
Dim newline() As String = sr.ReadLine.Split(","c)
' MsgBox(newline.Count)
' dt.Columns.AddRange({New DataColumn(newline(0)),
' New DataColumn(newline(1)),
' New DataColumn(newline(2))})
Dim i As Integer
For i = 0 To newline.Count - 1
dt.Columns.AddRange({New DataColumn(newline(i))})
Next
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(","c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1)}
dt.Rows.Add(newrow)
End While
dgv.DataSource = dt
End Sub
Columns and item values can be added to a DataTable individually, using dt.Columns.Add and newrow.Item, so that these can be done in a loop instead of hard-coding for a specific number of columns. e.g. (this code assumes Option Infer On, so adjust as needed):
Public Function CsvToDataTable(csvName As String, Optional delimiter As Char = ","c) As DataTable
Dim dt = New DataTable()
For Each line In File.ReadLines(csvName)
If dt.Columns.Count = 0 Then
For Each part In line.Split({delimiter})
dt.Columns.Add(New DataColumn(part))
Next
Else
Dim row = dt.NewRow()
Dim parts = line.Split({delimiter})
For i = 0 To parts.Length - 1
row(i) = parts(i)
Next
dt.Rows.Add(row)
End If
Next
Return dt
End Function
You could then use it like:
Dim dt = CsvToDataTable("E:\test.txt", ";"c)
DG1.DataSource = dt
I'm trying to define a datarow to hold values and then add it to data set
indgv: datagridview with values in it
dsdetails: a dataset with a table named details
If indgv.Rows.Count > 0 Then
Dim dr As DataRow
dr = dsdetails.Tables("details").NewRow
For Each row As DataGridViewRow In indgv.Rows
dr("mat") = row.Cells("icode").Value
dr("dateoftrans") = Me.DateTimePicker1.Value
dr("numoftrans") = transnum.Text
dr("type") = 1
dr("doc") = doctyp.SelectedValue
dr("amount") = row.Cells("iamo").Value
dsdetails.Tables("details").Rows.Add(dr)
Next
adpdetails.Update(dsdetails, "details")
End If
running this causes the following error
Object reference not set to an instance of an object.
how to rephrase the declaration with 'New' to avoid the problen
BTW : when using new as the following
Dim dr As New DataRow = dsdetails.Tables("details").NewRow
it shows design time error
Type 'dsdetails.Tables' is not defined.
Try this code:
If indgv.Rows.Count > 0 Then
Dim tbl As DataTable = dsdetails.Tables("details")
Dim dr As DataRow
For Each row As DataGridViewRow In indgv.Rows
dr = tbl.NewRow 'Create a new row inside the loop!
dr("mat") = row.Cells("icode").Value
dr("dateoftrans") = Me.DateTimePicker1.Value
dr("numoftrans") = transnum.Text
dr("type") = 1
dr("doc") = doctyp.SelectedValue
dr("amount") = row.Cells("iamo").Value
tbl.Rows.Add(dr)
Next
adpdetails.Update(tbl)
End If
If all you need is to copy rows from one table to another, DataTable class has a Copy method you may want to use. It works like this:
Dim dtCopy As New DataTable()
dtCopy = dt.Copy()
If you have a datagridview control bound to a table, you could also use this form:
Dim dtCopy As New DataTable()
dtCopy = DirectCast(dataGridViewX1.DataSource, DataTable).Copy()
The Copy method will copy the datatable structure and the data.
If you want to copy the structure only without the data you could use Clone method.
I want to find a particular ID in a DataTable, I am using a DataView to filter the results, but how do I know which row in the original table the filter view corresponds to? Any ideas? In know I could use LINQ but I don't think this would help either?
Dim dt As New DataTable
Dim dv As New DataView(dt)
dv.RowFilter = "ID = 123"
If dv.Count = 1 Then
'which datarow in the original datatable is this?
End If
EDIT
I want to avoid having to loop through the DataTable to find this:
For r As Integer = 0 To dt.Rows.Count - 1
If CInt(dt.Rows(r).Item("ID")) = 123 Then
Debug.WriteLine("Found it at row " + r.ToString)
Exit For
End If
Next
Nothing could be easier:
Dim dr As DataRow = dv(0).Row
http://msdn.microsoft.com/en-us/library/system.data.datarowview.row%28v=VS.100%29.aspx
Edit: According to your comment, you could use following to get the index of the row
Dim rowIndex As Int32 = -1
For i As Int32 = 0 To dr.Table.Rows.Count - 1
If dr.Table.Rows(i)("ID").Equals(dr("ID")) Then
rowIndex = i
Exit For
End If
Next
Or in this shorter way:
Dim rowIndex As Int32 = dr.Table.Rows.IndexOf(dr)
http://msdn.microsoft.com/en-us/library/system.data.datarowcollection.indexof.aspx