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.
Related
Right now, I'm developing web application using DevExpress BootstrapChart (v17.2.13.0) and I have binded the control with object datasource. Here is the example data used to be displayed in the graph:
Here is my objectives:
The graph will show the values of "ademand_im" and "rdemand_im" in different panes (I named them pane "A" and "B")
Each pane has "data_time" (date and time) as X-axis and the values ("ademand_im" or "rdemand_im") as Y-axis
Also, the values in each pane will be grouped by "hardware_id" so, in this case, there should be 2 line series of "83245551" and "88310991" in each pane (Note that "hardware_id" can be varied from time to time).
So the graph should look like this:
However, what I only acheive at this moment is that either the line series are shown in both panes but not grouped or not show anything in the graph.
Here is my code:
<dx:BootstrapChart ID="chart" ClientInstanceName="chart" runat="server"
DataSourceID="ods_ChartData" Height="640px" TitleText="Chart Data" CrosshairEnabled="true" Panes="A,B">
<ClientSideEvents Init="OnChartInit" />
<SettingsToolTip Shared="true" Enabled="true" OnClientCustomizeTooltip="ChartToolTip" />
<ArgumentAxis ArgumentType="System.DateTime" GridVisible="True" MinorGridVisible="True"
TickVisible="True" MinorTickVisible="True" TickInterval="1" MinorTickCount="3" TitleText="Date">
<Label DisplayMode="Rotate" RotationAngle="-0" Format-Formatter="FormatDate" />
</ArgumentAxis>
<ValueAxisCollection>
<dx:BootstrapChartValueAxis Pane="A" TitleText="ademand_im" />
<dx:BootstrapChartValueAxis Pane="B" TitleText="rdemand_im" />
</ValueAxisCollection>
<SettingsCommonSeries Type="Line" ArgumentField="data_time" Point-Size="0" />
<SettingsSeriesTemplate NameField="hardware_id" />
<SeriesCollection>
<dx:BootstrapChartLineSeries Pane="A" ValueField="ademand_im" />
<dx:BootstrapChartLineSeries Pane="B" ValueField="rdemand_im" />
</SeriesCollection>
</dx:BootstrapChart>
In this code, if I remove the "SettingsSeriesTemplate" line, the data will show in both panes but only in single line in each pane. However, if I keep this line the graph will not show anything.
After I tried to understand how this control works, the only solution I found is that I have to pivot "hardware_id" columns into "ademand_im" and "rdemand_im" values, which may be not the ideal one.
So instead of having "hardware_id", "ademand_im" and "rdemand_im" columns, the table should be transformed to have like "ademand_im_83245551", "ademand_im_88310991", "rdemand_im_83245551" and "rdemand_im_88310991" columns instead.
This is how the table after transforming looks like:
Here is the function codes that I used to transform the table (VB.NET):
<Extension()>
Public Function PivotDataTableColumnGroup(srcData As DataTable, rowGroupField As String, pivotColumnField As String, valueGroupFields As IEnumerable(Of String),
Optional ValueGroupColumnName As Func(Of String, String, String) = Nothing,
Optional otherFields As IEnumerable(Of String) = Nothing,
Optional GetOtherFieldValue As Func(Of DataTable, String, Object, Object) = Nothing
) As DataTable
Dim groupValueList As List(Of Object) = srcData.GetDistinctValuesByColumnName(rowGroupField)
Dim pivotValueList As List(Of Object) = srcData.GetDistinctValuesByColumnName(pivotColumnField)
Dim hasOtherFieldColumn As Boolean = Not (otherFields Is Nothing Or GetOtherFieldValue Is Nothing)
Dim dt As New DataTable
With dt
.Columns.Add(rowGroupField, srcData.Columns(rowGroupField).DataType)
For i As Integer = 0 To valueGroupFields.Count - 1
For j As Integer = 0 To pivotValueList.Count - 1
Dim columnName As String = GetColumnNameFromGroupFieldAndPivotValues(valueGroupFields(i), pivotValueList(j), ValueGroupColumnName)
dt.Columns.Add(columnName, srcData.Columns(valueGroupFields(i)).DataType)
Next
Next
If hasOtherFieldColumn Then
For i As Integer = 0 To otherFields.Count - 1
.Columns.Add(otherFields(i), srcData.Columns(otherFields(i)).DataType)
Next
End If
For i As Integer = 0 To groupValueList.Count - 1
Dim currentGroupValue As Object = groupValueList(i)
Dim dr As DataRow = dt.NewRow()
dr(rowGroupField) = currentGroupValue
If hasOtherFieldColumn Then
For j As Integer = 0 To otherFields.Count - 1
dr(otherFields(j)) = DBNullIfNothing(GetOtherFieldValue(srcData, otherFields(j), currentGroupValue))
Next
End If
For j As Integer = 0 To valueGroupFields.Count - 1
Dim currentField As String = valueGroupFields(j)
For k As Integer = 0 To pivotValueList.Count - 1
Dim currentPivotValue As Object = pivotValueList(k)
Dim columnName As String = GetColumnNameFromGroupFieldAndPivotValues(valueGroupFields(j), pivotValueList(k), ValueGroupColumnName)
Dim value As Object = (From row In srcData.AsEnumerable
Where row(rowGroupField) = currentGroupValue _
AndAlso row(pivotColumnField) = currentPivotValue
Select row(currentField)
).FirstOrDefault
dr(columnName) = DBNullIfNothing(value)
Next
Next
dt.Rows.Add(dr)
Next
End With
Return dt
End Function
<Extension()>
Public Function GetDistinctValuesByColumnName(dt As DataTable, columnName As String) As List(Of Object)
Dim valueList As List(Of Object) = (From row As DataRow In dt.AsEnumerable
Where Not IsDBNull(row(columnName))
Order By row(columnName)
Select row(columnName) Distinct
).ToList
Return valueList
End Function
Private Function GetColumnNameFromGroupFieldAndPivotValues(groupField As String, pivotValue As Object, Optional ValueGroupColumnName As Func(Of String, String, String) = Nothing) As String
Dim columnName As String = groupField & "_" & pivotValue.ToString()
If ValueGroupColumnName IsNot Nothing Then
columnName = ValueGroupColumnName(groupField, pivotValue)
End If
Return columnName
End Function
Public Function DBNullIfNothing(o As Object) As Object
If o Is Nothing Then Return DBNull.Value
Return o
End Function
And this is how I used the function to transform the table:
Dim chartData As DataTable = result.PivotDataTableColumnGroup("data_time", "hardware_id", {"ademand_im", "rdemand_im"}, Nothing, Nothing, Nothing)
ResultChartData = chartData 'Stored in ASPxHiddenField in JSON form
After that, instead of setting chart series properties in aspx file, I have to add chart series manually in code behind:
Private Sub chart_LoadProfile_DataBound(sender As Object, e As EventArgs) Handles chart_LoadProfile.DataBound
Using ResultChartData
Dim seriesList As List(Of String) = (From col As DataColumn In ResultChartData.Columns
Where col.ColumnName <> "data_time"
Order By col.ColumnName
Select col.ColumnName
).ToList
Dim hardWardCount As Integer = (From s In seriesList Where s.Contains("ademand_im_")).Count
Dim showInLegend As Boolean = hardWardCount > 1
With chart_LoadProfile.SeriesCollection
.Clear()
For i As Integer = 0 To seriesList.Count - 1
Dim fieldName As String = seriesList(i)
Dim hardwareId As String = seriesList(i).Split("_")(2)
Dim series As New BootstrapChartLineSeries
With series
.ArgumentField = "data_time"
.ValueField = fieldName
.Point.Size = 0
.ShowInLegend = showInLegend
If fieldName.Contains("ademand_im_") Then
.Pane = "A"
.Name = "kW - " & hardwareId
Else
.Pane = "B"
.Name = "kVar - " & hardwareId
End If
End With
.Add(series)
Next
End With
End Using
End Sub
In my ASP.NET application, i need to read the CSV file and insert into sql server.
and it was strange that it treat the 1st row (column name) as LineNumber=2.
but i found that my code cannot read the last row of the CSV file.
Dim CSV_content As String = ""
Dim CSVFilePathName As String = Server.MapPath("~/XXX/" & filename)
If File.Exists(CSVFilePathName) = True Then
'Response.Write("exists")
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(CSVFilePathName)
Dim CurrentRecord As String()
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {","}
afile.HasFieldsEnclosedInQuotes = True
Dim LastName As String = ""
Dim FirstName As String = ""
Dim DisplayName As String = ""
Dim EmailName As String = ""
Dim dc As New dcHRISDataContext
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
'insert into tmp db
If afile.LineNumber > 2 Then
Dim newRecord1 As New XXX
dc.XXX.InsertOnSubmit(newRecord1)
newRecord1.LastName = CurrentRecord(0).Trim
newRecord1.FirstName = CurrentRecord(1).Trim
newRecord1.DisplayName = CurrentRecord(1).Trim
newRecord1.DirEmail = CurrentRecord(3).Trim
newRecord1.GetFileDate = DateTime.Now
newRecord1.GetFileName = filename
dc.SubmitChanges()
End If
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
End If
Wow, this is the dumbest issue that I have seen.
Anyhow, Apparently the last row in the TextFieldParser is -1, and not LastRowWithValuesIndex + 1. So what happens is this.
You read the data of the last line (this is fine)
The reader skips to the next line to prepare the next line to read (this is fine)
You get the afile.LineNumber, now set to the next line. Which is -1
at this point. (this is dumb although understandable, not your fault)
Your if statement wont let you in because hey you are on line -1.
Loop ends, skipping last row in the CSV.
All you have to do is to read the line number of the row before reading the data:
Dim i As Integer = afile.LineNumber
CurrentRecord = afile.ReadFields
If i > 2 Then
etc
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 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()
I have a problem.
Dim Maxis As String
'Dim MaxisExtra As String
Dim b As New ArrayList
Dim WS As New WebService1.Service1
Dim cnt As String
Dim MRWS As New MobileReload_WS.MobileReload_WS
cnt = WS.StockCountTelco(1, Session("Maxis"))
If CInt(cnt) >= CInt(DropDownList1.SelectedItem.Text) Then
Dim sLock As String
sLock = MRWS.LockAStock(1, 1, "Online", Session("Maxis"), DropDownList1.SelectedItem.Text)
Session("sLock") = sLock
If sLock = "" Then
PopupMsgBox("Unable to allocate Stock")
Else
Maxis = "Maxis" & ";" & Session("Maxis") & ";" & DropDownList1.SelectedItem.Text & ";" & Session("Cost")
'If MaxisExtra = "" Then
' b.Add(Maxis)
' Elseif
' MaxisExtra = MaxisExtra + Maxis
' b.Add(MaxisExtra)
'End If
End If
Else
PopupMsgBox("Not enough stock")
End If
b.Add(Maxis)
Session("Transaction") = b
End Sub
The first time i enter the string into the arraylist it is okay. But when the user press the button add again the second time, it replace the first string. Can anyone help me how to save the string into the second slot based on my coding?
If you're talking about the b ArrayList, then you're creating a new one each time and storing the new ArrayList in Session("Transaction")
Maybe you mean something like this instead...
Dim b as ArrayList = Session("Transaction")
If b Is Nothing Then
b = new ArrayList
End If
...
Session("Transaction") = b
Although it's difficult to say exactly, because your code is very messy and not clear
You put the array list in a session variable, but you never read it back. You create a new array list each time, so it will always be empty and replace the previous one.
Get the array list from the session variable if there is one:
Dim b As ArrayList = Session("Transaction")
If b Is Nothing Then b = New ArrayList