I am loading three dataset from the database which has
Dataset 1 > Table 1 > 10 rows
Dataset 2 > Table 1 > 3 rows
Dataset 3 > Table 1 > 5 rows
(All dataset has same column name, same datatype) actually they contains the data based on different select condition)
now I want to merge all three dataset into one like this
Dataset 4 > Table 1 > 18 rows
Please help how can I do it
Try the DataSet.Merge Method (DataSet) method. Something like this (not tested):
C#:
dataset1.Merge(dataset2);
DataSet dataset4 = dataset1.Merge(dataset3);
VB.NET:
dataset1.Merge(dataset2)
Dim dataset4 As New DataSet = dataset1.Merge(dataset3)
You can use Tim's suggestion if you're looking to merge the two datasets and all of the containing tables, or you can do something like this for specific tables.
DataTable table1 = new DataTable();
DataTable table2 = new DataTable();
DataTable table3 = new DataTable();
table1.Merge(table2);
table1.Merge(table3);
One (flexible) way is using Enumerable.Union.
In VB.NET:
Dim tblMerged = tbl1.AsEnumerable _
.Union(tbl2.AsEnumerable) _
.Union(tbl3.AsEnumerable) _
.CopyToDataTable()
Tested with:
Dim tbl1 As New DataTable
Dim tbl2 As New DataTable
Dim tbl3 As New DataTable
Dim col1_1 As New DataColumn("Col1", GetType(String))
Dim col2_1 As New DataColumn("Col1", GetType(String))
Dim col3_1 As New DataColumn("Col1", GetType(String))
tbl1.Columns.Add(col1_1)
tbl2.Columns.Add(col2_1)
tbl3.Columns.Add(col3_1)
For i As Int32 = 1 To 10
Dim row = tbl1.NewRow
row(0) = "Tbl1_Value" & i
tbl1.Rows.Add(row)
Next
For i As Int32 = 1 To 20
Dim row = tbl2.NewRow
row(0) = "Tbl2_Value" & i
tbl2.Rows.Add(row)
Next
For i As Int32 = 1 To 50
Dim row = tbl3.NewRow
row(0) = "Tbl3_Value" & i
tbl3.Rows.Add(row)
Next
Dim tblMerged = tbl1.AsEnumerable.Union(tbl2.AsEnumerable).Union(tbl3.AsEnumerable).CopyToDataTable
Related
I need to append a row from databla1 to datatable2 that has already rows, I tried to importrow(), clone(), but I cant' find the solution:
The datatable1 has this structure:
name | surname | iddepartment | address | phone1 | phone2 | country | cp | birthdate |
And the datatable2 is a public datatable created inside a class:
Public Shared datable2 As New DataTable
I have this code:
Dim datatable1 As DataTable = getdata("myQuery")
I tried to do this but I get an error:
Dim newRow= datatable1.Rows(0)
myClass.datatable2.rows.add(newRow)
How can I do this? thanks
As far as I understand.
VB.NET Sample :
'db query result'
table.Columns.Add("Name", GetType(String))
table.Columns.Add("surname", GetType(String))
table.Columns.Add("iddepartment", GetType(Integer))
table.Columns.Add("phone1", GetType(String))
table.Columns.Add("phone2", GetType(String))
table.Columns.Add("country", GetType(String))
table.Columns.Add("cp", GetType(String))
table.Columns.Add("birthdate", GetType(DateTime))
'column set'
Dim table2 As DataTable = table
Dim i As Integer = 0
'add dummy data'
For index = 1 To 10
'instance new dataRow '
Dim dr As DataRow = table2.NewRow
dr("Name") = "Jack"
dr("surname") = "Daniels"
dr("iddepartment") = i
dr("phone1") = "099999"
dr("phone2") = "09999"
dr("country") = "USA"
dr("cp") = "-"
dr("birthdate") = New DateTime
table2.Rows.Add(dr)
i = i + 1
Next
'each table2 rows'
For Each rowItem As DataRow In table2.Rows
Console.WriteLine(rowItem("Name"))
Console.WriteLine(rowItem("surname"))
Console.WriteLine(rowItem("iddepartment"))
Console.WriteLine(rowItem("phone1"))
Console.WriteLine(rowItem("phone2"))
Console.WriteLine(rowItem("country"))
Console.WriteLine(rowItem("cp"))
Console.WriteLine(rowItem("birthdate"))
Next
Console.Read()
Datatable Example Source Link : https://www.dotnetperls.com/datatable-vbnet
I have 2 datatable objects (dt1,dt2), which have a common filed called "File_Name". I want to create a datatable (dtFinal), combining the two datatables to be used in gridview of asp.net
Each of the tables (dt1,dt2) can have overlapping column header names, meaning if dt1 has a header as "plant_code" dt2 can also have the header as "plant_Code" but not mandatory.
My objective is to have a common datatable (dtFinal) with all the headers from all the individual datatables.
I tried something like this
Dt1.PrimaryKey = New DataColumn() {Dt1.Columns(System.AppDomain.CurrentDomain.BaseDirectory & "\resources\files\" & "GRN" & ".csv")}
Dt2.PrimaryKey = New DataColumn() {Dt1.Columns(System.AppDomain.CurrentDomain.BaseDirectory & "\resources\files\" & "Payment Data" & ".csv")}
Dt1 = CsvToDataTable(System.AppDomain.CurrentDomain.BaseDirectory & "\resources\files\" & "GRN" & ".csv")
Dt2 = CsvToDataTable(System.AppDomain.CurrentDomain.BaseDirectory & "\resources\files\" & "Payment Data" & ".csv")
ds.Tables.Add(Dt1)
ds.Tables.Add(Dt2)
Dim drel As New DataRelation("EquiJoin", Dt2.Columns("File_Name"), Dt1.Columns("File_Name"))
ds.Relations.Add(drel)
Dim jt As New DataTable("Joinedtable")
ds.Tables.Add(jt)
For Each dr As DataRow In ds.Tables("Table1").Rows
Dim parent As DataRow = dr.GetParentRow("EquiJoin")
Dim current As DataRow = jt.NewRow()
' Just add all the columns' data in "dr" to the New table.
For i As Integer = 0 To ds.Tables("Table1").Columns.Count - 1
current(i) = dr(i)
Next
' Add the column that is not present in the child, which is present in the parent.
current("Dname") = parent("Dname")
jt.Rows.Add(current)
Next
DtFinal = ds.Tables("Joinedtable")
Creating a dataset and a relation between dt1 and dt2 ...But this doesn't seem to work and giving me an error in line 1 instance of object to be declared using New.
Has someone tried something like this in Vb ? Or can my code be edited to make it work.
Further info: each datatable tb1 and tb2 have unique values in the File_Name column which is the first column. and hence can be selected as the primary key.
When you say, "Merge" it may mean one thing or another. For example, I may think of this method.
This is Working Code:
Public Sub MergeTables()
Dim t1 As New DataTable("T1")
t1.Columns.Add("C1", GetType(String))
t1.Columns.Add("C2", GetType(String))
t1.Columns.Add("C3", GetType(String))
Dim t2 As New DataTable("T2")
t2.Columns.Add("C1", GetType(String)) 'same column
t2.Columns.Add("C2", GetType(Integer)) ' same column, different data type
t2.Columns.Add("C4", GetType(String)) ' different column
Dim map As New Dictionary(Of String, String)
Dim t3 As New DataTable("T4")
MergeColumns(t3, t1, map)
MergeColumns(t3, t2, map)
Debug.WriteLine("Should be 5 columns and reality is: " & t3.Columns.Count)
' Add some data
t1.Rows.Add({"data from t1 c1", "data from t1 c2", "data from t1 c3"})
t2.Rows.Add({"data from t2 c1", 55, "data from t2 c3"})
MergeRows(t3, t1, map)
MergeRows(t3, t2, map)
t3.AcceptChanges()
For Each row As DataRow In t3.Rows
Debug.WriteLine(String.Join(";", row.ItemArray.Select(Function(o) o.ToString()).ToArray()))
Next
End Sub
Private Sub MergeColumns(totbl As DataTable, fromtbl As DataTable, map As Dictionary(Of String, String))
For Each c As DataColumn In fromtbl.Columns
If Not totbl.Columns.Contains(c.ColumnName) Then
totbl.Columns.Add(c.ColumnName, c.DataType)
map.Add(c.Table.TableName & "_" & c.ColumnName, c.ColumnName)
ElseIf Not totbl.Columns(c.ColumnName).DataType.Equals(c.DataType) Then
totbl.Columns.Add(c.Table.TableName & "_" & c.ColumnName, c.DataType)
map.Add(c.Table.TableName & "_" & c.ColumnName, c.Table.TableName & "_" & c.ColumnName)
Else
map.Add(c.Table.TableName & "_" & c.ColumnName, c.ColumnName)
End If
Next
End Sub
Private Sub MergeRows(totbl As DataTable, fromtbl As DataTable, map As Dictionary(Of String, String))
For Each row As DataRow In fromtbl.Rows
Dim newRow As DataRow = totbl.NewRow()
For Each c As DataColumn In fromtbl.Columns
newRow(map(fromtbl.TableName & "_" & c.ColumnName)) = row(c.ColumnName)
Next
totbl.Rows.Add (newRow)
Next
End Sub
Result:
data from t1 c1 ; data from t1 c2 ; data from t1 c3 ; ;
data from t2 c1 ; ; ; 55 ; data from t2 c3
But may be, you need something else. However, this is good example how to do thing like this
You could try the DataTable Merge.
dt3 = new DataTable();
dt3 .Merge(dtOne);
dt3 .Merge(dtTwo);
Look at this post for more info/solutions. Merge 2 DataTables and store in a new one
I have 2 comboboxes, cmbstud and cmbhostel. They are filled from the database by binding the datasource to the datatable. As I update, the cmbstud updates accordingly. When I update the last record the datatable empties, but cmbstud still retains the value. Cmbhostel data is bound to change index of cmbstud.
In the form load event I have this code:
Dim cmd As New SqlCommand("SELECT stud_id,name FROM student_details WHERE stud_id NOT IN (SELECT stud_id FROM student_details WHERE hostel_id!=0)", sqlcont.Conn)
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim dat As New DataTable
Dim j As Integer
For j = 0 To dat.Rows.Count - 1
dr.Read()
Next
dat.Load(dr)
cmbstud.DisplayMember = "name"
cmbstud.ValueMember = "stud_id"
cmbstud.DataSource = New BindingSource(dat, Nothing)
dr.Close()
sqlcont.Conn.Close()
In my btnhostel for updating I have the following queries implemented and the following code to reload the form to refresh my datasources:
"UPDATE hostel SET in_use=in_use+1 WHERE hostel_id=#hostid"
"UPDATE student_details SET hostel_id=#hostid where stud_id=#stud_id"
frmallocateHostel_Load(Nothing, Nothing)
Cmbstud index change evnt code:
Dim sqcm5 As New SqlCommand("Select hostel.hostel_id,hostel.hostel_name From hostel Inner Join student_details On student_details.gender = hostel.hostel_gender where student_details.stud_id =" & cmbstud.SelectedValue.ToString & " ", sqlcont.Conn)
Dim datreadr5 As SqlDataReader = sqcm5.ExecuteReader
Dim dt5 As New DataTable
Dim n As Integer
For n = 0 To dt5.Rows.Count - 1
datreadr5.Read()
Next
dt5.Load(datreadr5)
cmbhostel.ValueMember = "hostel_id"
'asign value & display member b4 datasource to avoid errors
cmbhostel.DisplayMember = "hostel_name"
cmbhostel.DataSource = dt5
There are some similar questions: ComboBox has its old value after Clear(); however, they don't address my issue.
changing this did the trick:
Dim b As New BindingSource()
b.DataSource = dat
cmbstud.DataSource = b
b.ResetBindings(False)
i have 2 table in my dataset, what i trying to achieve is convert 2 table item into string
Public Shared Function mtdCDsToStr(ByVal pDataSet As DataSet) As String
Dim sDs As String
Dim sb As New System.Text.StringBuilder
Dim drRow As DataRow
Dim dcColumn As DataColumn
Dim dtTable As DataTable
Dim x As Integer = 0
For Each dtTable In pDataSet.Tables
For Each drRow In pDataSet.Tables(x).Rows
Dim colName(pDataSet.Tables(x).Columns.Count) As String
Dim i As Integer = 0
For Each dcColumn In pDataSet.Tables(0).Columns
colName(i) = dcColumn.ColumnName
sb.Append(colName(i) + "," + drRow(colName(i)).ToString + ",")
i += 1
Next
sb.Append("|")
Next
x += 1
sb.Append("$")
Next
sDs = sb.ToString
Return sDs
End Function
code explanation
the function is to pass in a dataset and convert the dataset into a string
what i trying to achieve is convert multiple datatable into a string but i can only loop one table in my code above, what should i do in order to loop multi table? =(
change as below
For Each dtTable As DataTable In dataSet.Tables
For Each dr As DataRow In dtTable.Rows
For Each column As DataColumn In dtTable.Columns
sb.Append(column.ColumnName + "," & dr(column.ColumnName).ToString() & ",")
Next
sb.Append("|")
Next
sb.Append("$")
Next
But rather than converting DataSet to string you may try to get XML from DataSet. I'm Not sure What is the exact requirement you converting to sting, but XML will be good way to communicate Data.
xmlString =lpDataSet.GetXml()
The following code adds, dynamically, tabs to a tab control. In each row of datatable, it calls a function CarregaAvaliacoes that adds some controls to each tab. Dataset dtGruposCompetencias has 4 rows. However, after first row (after calling CarregaAvaliacoes), it looses data (IndexOutOfRangeException). Any ideias?
EDIT: I have debugged it, followed each step. After finishing CarregaAvaliacoes first time, dataset has no longer data. Don't understand why.
Thanks!
Dim dtGruposCompetencias As New DataTable
Dim nivel As Integer = 4
dtGruposCompetencias = dal.CarregaAvaliacoesPorNivel(nivel)
lblTemp.Text = dtGruposCompetencias.Rows.Count
If dtGruposCompetencias.Rows.Count > 0 Then
Dim tb As AjaxControlToolkit.TabPanel
For i As Integer = 0 To dtGruposCompetencias.Rows.Count - 1
tb = New AjaxControlToolkit.TabPanel
tb.HeaderText = dtGruposCompetencias.Rows(i)("designacao").ToString()
Dim grupo As String = dtGruposCompetencias.Rows(i)("idGrupoCompetencia").ToString()
CarregaAvaliacoes(tb, grupo)
Next
tabAvaliacoes.ActiveTabIndex = 0
Else
lblSemAvaliacoes.Visible = True
End If
Public Sub CarregaAvaliacoes(tab As AjaxControlToolkit.TabPanel, idGrupoCompetencia As String)
Dim dtAtributos As New DataTable
dtAtributos = dal.CarregaAtributosAvaliacao(idGrupoCompetencia)
If dtAtributos.Rows.Count > 0 Then
Dim tdCompetencia As TableCell, tdAtributo As TableCell
Dim tr As TableRow
Dim tblAvaliacao As New Table
For i As Integer = 0 To dtAtributos.Rows.Count - 1
tdCompetencia = New TableCell
tdCompetencia.Controls.Add(fRetTexto(dtAtributos.Rows(i)("competencia").ToString()))
tdAtributo = New TableCell
tdAtributo.Controls.Add(fRetTexto(dtAtributos.Rows(i)("atributo").ToString()))
tr = New TableRow
tr.Cells.Add(tdCompetencia)
tr.Cells.Add(tdAtributo)
tblAvaliacao = New Table
tblAvaliacao.Rows.Add(tr)
Next
tab.Controls.Add(tblAvaliacao)
Else
Dim lblSemRegistos As New Label
lblSemRegistos.Text = "Sem dados para avaliação."
tab.Controls.Add(lblSemAvaliacoes)
End If
End Sub