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()
Related
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 a Function which returns DataTable Like this (if there are Rows)...
Protected Function getAideData() As DataTable
Dim dt As DataTable = DAL.ReturnData("select * from pg_PersonalInfo P Left Join pg_employeeInterview E on E.sesID = P.sesID ")
If dt.Rows.Count > 0 Then
Return dt
End If
End Function
Then later in my page I accress it like this:
Dim d as datatable = getAideData
Here is my problem: If I have Data in Datatable then I have no problem, however if I dont have any data returned from my method then there is a issue.
I guess my question is, if I have a Function and that cannot return a datatable (no rows), then what should I return from my function? So i can handle the data properly later in my application.
I guess my question is, if I have a Function and that cannot return a
datatable (no rows), then what should I return from my function?
Return Nothing
Protected Function getAideData() As DataTable
Dim dt As DataTable = DAL.ReturnData("select * from pg_PersonalInfo P Left Join pg_employeeInterview E on E.sesID = P.sesID ")
If dt.Rows.Count > 0 Then
Return dt
End If
Return Nothing
End Function
Function GetDataTable(ByVal qry As String) As DataTable
Dim DbCon As New OleDb.OleDbConnection
Try
Dim ConStr As String
ConStr = System.Configuration.ConfigurationManager.AppSettings("ConnCMSTrend").ToString()
DbCon.ConnectionString = ConStr
DbCon.Open()
Dim queryString As String = qry
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(queryString, ConStr)
Dim res As DataSet = New DataSet
adapter.Fill(res)
DbCon.Close()
GetCMSTrend = res.Tables(0)
Catch ex As Exception
DbCon.Close()
End Try
End Function
'Note That you need to add the connection string in the appsettings file. In the above case ConnCMSTrend is the database connection string.
I have a datatable that returns a column name location which is a combination of city,state and zipcode,i have stored that column values in an array. now i want to split the array data and store in another array.
here is the code but it is not working.
Dim eTemp As DataTable = dt.DefaultView.ToTable(True, "Location")
Dim s() As String
Dim Count As Integer = PortCodeTemp.Rows.Count - 1
ReDim s(0 To Count)
For i = 0 To Count
s(i) = PortCodeTemp.Rows(i).Item("Location")
For t As Integer = 0 To Count
Dim items As String() = s.Split(",".ToCharArray())
Next
Next
Your issue is here
Dim items As String() = s.Split(",".ToCharArray())
because there is no Split method for an array.
I think you meant to split the string at index i, which is where you stored the string value of location.
Dim items As String() = s(i).Split(",".ToCharArray())
Update
I'm not sure why you're doing it this way but here is something you can try. Instead of using an array I just used a List(Of String) so there's no need to be doing a redim in every loop.
Dim allItems As New List(Of String)
For i = 0 To PortCodeTemp.Rows.Count - 1
Dim location as String = PortCodeTemp.Rows(i).Item("Location")
allItems.AddRange(location.Split(",".ToCharArray()))
Next
Therefore, allItems should contain everything.
I have access db with 3 different tables,I want to load the whole database into dataset so I will be able to work with the data without load the db serval times.
all the examples of working with dataset are showing how to get part of the database using ".fill"
for example :
OleDbCommand CommandObject = new OleDbCommand ("Select * from employee");
OleDbAdapter myDataAdapter = new OleDbAdapter (null, con);
myDataAdapter.SelectCommand = CommandObject;
myDataAdapter.Fill (myDataSet, "EmployeeData");
this example load only from employee but how can I etrieve the all tables in once into dataset?
in xml for instance there is command to load all the document to dataset with:" dataset.ReadXml"
How can I achive it in access db?
Thanks for any help
Baaroz
Protected Function getDataSetAndFill(ByRef connection As OleDb.OleDbConnection,
Optional ByVal isExportSchema As Boolean = True) As DataSet
Dim myDataSet As New DataSet
Dim myCommand As New OleDb.OleDbCommand
Dim myAdapter As New OleDb.OleDbDataAdapter
myCommand.Connection = connection
'Get Database Tables
Dim tables As DataTable = connection.GetOleDbSchemaTable( _
System.Data.OleDb.OleDbSchemaGuid.Tables, _
New Object() {Nothing, Nothing, Nothing, "TABLE"})
'iterate through all tables
Dim table As DataRow
For Each table In tables.Rows
'get current table's name
Dim tableName As String = table("TABLE_NAME")
Dim strSQL = "SELECT * FROM " & "[" & tableName & "]"
Dim adapter1 As New OleDb.OleDbDataAdapter(New OleDb.OleDbCommand(strSQL, connection))
adapter1.FillSchema(myDataSet, SchemaType.Source, tableName)
'Fill the table in the dataset
myCommand.CommandText = strSQL
myAdapter.SelectCommand = myCommand
myAdapter.Fill(myDataSet, tableName)
Next
''''''''''''''''''''''''''''''''''''''
'''' Add relationships to dataset ''''
''''''''''''''''''''''''''''''''''''''
'First, get relationships names from database (as well as parent table and child table names)
Dim namesQuery As String = "SELECT DISTINCT szRelationship, szReferencedObject, szObject " & _
"FROM MSysRelationships"
Dim namesCommand As New System.Data.OleDb.OleDbCommand(namesQuery, connection)
Dim namesAdapter As New System.Data.OleDb.OleDbDataAdapter(namesCommand)
Dim namesDataTable As New DataTable
namesAdapter.Fill(namesDataTable)
'Now, get MSysRelationship from database
Dim relationsQuery As String = "SELECT * FROM MSysRelationships"
Dim command As New System.Data.OleDb.OleDbCommand(relationsQuery, connection)
Dim adapter As New System.Data.OleDb.OleDbDataAdapter(command)
Dim relationsDataTable As New DataTable
adapter.Fill(relationsDataTable)
Dim relationsView As DataView = relationsDataTable.DefaultView
Dim relationName As String
Dim parentTableName As String
Dim childTablename As String
Dim row As DataRow
For Each relation As DataRow In namesDataTable.Rows
relationName = relation("szRelationship")
parentTableName = relation("szReferencedObject")
childTablename = relation("szObject")
'Keep only the record of the current relationship
relationsView.RowFilter = "szRelationship = '" & relationName & "'"
'Declare two arrays for parent and child columns arguments
Dim parentColumns(relationsView.Count - 1) As DataColumn
Dim childColumns(relationsView.Count - 1) As DataColumn
For i As Integer = 0 To relationsView.Count - 1
parentColumns(i) = myDataSet.Tables(parentTableName). _
Columns(relationsView.Item(i)("szReferencedColumn"))
childColumns(i) = myDataSet.Tables(childTablename). _
Columns(relationsView.Item(i)("szColumn"))
Next
Dim newRelation As New DataRelation(relationName, parentColumns, childColumns, False)
myDataSet.Relations.Add(newRelation)
Next
If isExportSchema Then
Dim schemaName = GetXmlSchemaFileName()
If File.Exists(schemaName) Then File.SetAttributes(schemaName, FileAttributes.Normal)
myDataSet.WriteXmlSchema(schemaName)
End If
Return myDataSet
End Function
You should just call the OleDbDataAdapter.Fill method with different SelectCommands and pass the same DataSet but different table names inside. In this case, your dataSet will contain different filled tables.
I want to loop through my datatable column called SDESCR and created a string that looks like this.
Dim labels As String() = {"North", "South", "East", "West", "Up", "Down"}
this is what i am trying and it is not working
Dim labels As String()
For Each row As DataRow In tablegraph.Rows
labels = labels " ' " + row.Item("SDESCR") + " ',"
Next row
THANK YOU FOR THE HELP, I WILL TEST THEM TOMORROW AND SEE WHICH WORKS BEST AND MARK ONE CORRECT.
Do this instead
Dim labels As String()
Dim labelsList As List(Of String) = New List(Of String)
For Each row As DataRow In tablegraph.Rows
labelsList.Add(row.Item("SDESCR"))
Next
labels = labelsList.ToArray()
If you need it to be a comma delimited list instead you can just do
Dim commaLabels As String = String.Join(labels, ",")
If you need them stored in an array, then you can add them to a list and then call the ToArray() method on the list:
Dim labelList As New List(Of String)
For Each row As DataRow In tablegraph.Rows
labelList.Add(row.Item("SDESCR"))
Next row
Dim labels As String() = labelList.ToArray()
If you want a string, use this (string builder is best due to memory management issues with constant string declaration.
Dim labels As New StringBuilder()
For Each row As DataRow In tablegraph.Rows
labels.Append(" ' " + row.Item("SDESCR") + " ',")
Next row
Then when you need the string, use labels.ToString()
If you want an array, use this...
Dim labels As New List(Of String)()
For Each row As DataRow In tablegraph.Rows
labels.Add(row.Item("SDESCR"))
Next row
Then when you need the array, use labels.ToArray()
The main reason your above code is failing is that you are declaring an Array of strings.
If you mean a String-Array instead of a String, this works:
Dim labels(tablegraph.Rows.Count - 1) As String
For i As Int32 = 0 To tablegraph.Rows.Count - 1
labels(i) = tablegraph(i)("SDESCR").ToString
Next
If you want them separated with a comma, you can use a StringBuilder to append:
Dim labels As New System.Text.StringBuilder
For i As Int32 = 0 To tablegraph.Rows.Count - 1
labels.Append(" ' ").Append(tablegraph(i)("SDESCR").ToString).Append(" ',")
Next
If labels.Length <> 0 Then labels.Length -= 1 'remove last comma'
Dim labelString As String = labels.ToString
There are plenty of ways to do this; here is an approach using LINQ
Dim labels As String() = (From myRow In tablegraph _
Select CType(myRow.Item("SDESCR"), String)).ToArray
It's worth nothing that this will fail for NULL/NOTHING values of "SDESCR".
If you just want a single comma-separated values you can do this:
Dim sOutput = String.Join(",", (From myRow In tablegraph _
Select CType(myRow.Item("SDESCR"), String)).ToArray)
labels = labels " ' " + row.Item("SDESCR") + " ',"
^
Plus sign missing?
Also, when you do this you'll be left with an extra , at the end of your string. So you'll want to strip that off.