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.
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
I am using a csvReader in order to retrieve data from a csv file. My csv file consists of 500elements and I only need the first 300. How do I limit my csvReader in order to return only 300 elements?
Dim PressureTable As DataTable = GetDataTabletFromCSVFile(BackUpDirDminus1)
Console.WriteLine("Rows count:" + PressureTable.Rows.Count.ToString)
Console.ReadLine()
Using CSVReader As New TextFieldParser(BackUpDirDminus1)
CSVReader.SetDelimiters(New String() {","})
CSVReader.HasFieldsEnclosedInQuotes = True
'read column names
Dim colFields As String() = CSVReader.ReadFields()
'For Each column As String In colFields
While Not CSVReader.EndOfData
Dim fieldData As String() = CSVReader.ReadFields()
'Making empty value as null
For i As Integer = 0 To fieldData.Length-1
If fieldData(i) = "" Then
fieldData(i) = Nothing
End If
Next
PressureTable.Rows.Add(fieldData)
End While
End Using
Please help. Thanks
I suppose there should be a method name "ReadNextRecord()", so your while loop should be like
While CSVReader.ReadNextRecord()
Declare a int k =0
and do k++
Once K++ reaches 300, then you can End While.
I have a LINQ2Entity problem, I want to get the value, string, from a database, so I select FProducts.Serial_number, and to end the query, I do .ToDictionary.
The problem is, it tells me that it doesn't have sufficient parameters, to convert ToDictionary.
So I need something like select FProducts.Serial_number, Nothing). ToDictionary.
Also FProducts.Serial_number, 0).ToDictionary doesn't work.
Any recommendations?
Sub GetStatistics(ByVal ProductNumbers As List(Of String), ByRef Passed As Integer, ByRef FailedProducts As List(Of String))
Passed = 0
FailedProducts = Nothing
Dim tpDictionary As Dictionary(Of String, Integer)
For Each productNumber As String In ProductNumbers
Using context As New SelmaEntities
Dim Table = (From GoodProducts In context.TestResults
Where (GoodProducts.Art_no = productNumber)
Select GoodProducts.Art_no, GoodProducts.Failed)
tpDictionary = (From FProducts In context.TestResults
Where (FProducts.Art_no = productNumber And FProducts.Failed <> 0)
Order By FProducts.Serial_number
Select FProducts.Serial_number, ).ToDictionary
End Using
Next
End Sub
ToDictionary requires lambda expressions as parameters: one to select the dictionary key, one to select the value. So try:
tpDictionary = (From FProducts In context.TestResults
Where (FProducts.Art_no = productNumber And FProducts.Failed <> 0))
.ToDictionary(Function(p) FProducts.Serial_number, Function(p) 0)
var products = from p in FProducts select new { value=serial_number,key=productid};
Dictionary<string, int> dictionary = new Dictionary<string, int>();
foreach(var item in products){
dictionary.Add(item.value, item.key);
}
I have an 2-d arraylist with 2 fixed columns and dynamic rows. The arraylist will be assigned to the session variable at the end of the code below. My question is how can loop thorugh the arraylist from the session to get its value?
If .SQLDS.Tables(.sSQLDSTbl).Rows.Count > 0 Then
Dim NoOfAdjType(1, .SQLDS.Tables(.sSQLDSTbl).Rows.Count - 1)
For iRow As Integer = 0 To .SQLDS.Tables(.sSQLDSTbl).Rows.Count - 1
If Not .SQLDS.Tables(.sSQLDSTbl).Rows(iRow).Item("i_commAmt") Is System.DBNull.Value Then
NoOfAdjType(0, iRow) = .SQLDS.Tables(.sSQLDSTbl).Rows(iRow).Item("productType")
NoOfAdjType(1, iRow) = Format(.SQLDS.Tables(.sSQLDSTbl).Rows(iRow).Item("i_commAmt"), "#,##0.00")
End If
Next
Session("iNoOfAdjAmtType") = NoOfAdjType
End If
I have tried this but it's giving me error 'Too many arguments to 'Public Overridable Default Property Item(index As Integer) As Object'
Dim NoOfAdjType As ArrayList = CType(Session("iNoOfAdjAmtType"), ArrayList)
For i As Integer = 0 To NoOfAdjType.Count
Dim a As String = NoOfAdjType(0, i)
Dim b As String = NoOfAdjType(1, i)
Next
The type you are dealing with is Object(,). So when reading from the session you can cast it back to this type.
Here's an article on MSDN which illustrates how to read values from session:
Dim NoOfAdjType as Object(,) = CType(Session("iNoOfAdjAmtType"), Object(,))
' do something with the list
And if you wanted to perform the check safely ensuring that there is an item with the given id in the session:
If Session.Item("iNoOfAdjAmtType") IsNot Nothing Then
' We have a value in the session with the given id
Dim NoOfAdjType as Object(,) = CType(Session("iNoOfAdjAmtType"), Object(,))
End If
I am not certain what is the data-type of array, but this how you manipulate the multi-dimension arrays in VB.NET assuming data-type as object
' declaring variable of multi-dim array
Dim NoOfAdjType As Object(,)
' create array object of needed dimension (you may use redim keyword)
NoOfAdjType = new Object(1, .SQLDS.Tables(.sSQLDSTbl).Rows.Count - 1) {}
...
' push it in session
Session("iNoOfAdjAmtType") = NoOfAdjType
...
' get back from session
NoOfAdjType = DirectCast(Session("iNoOfAdjAmtType"), Object(,))
...
For i As Integer = 0 To NoOfAdjType.GetLength(0)
For j As Integer = 0 To NoOfAdjType.GetLength(1)
Dim a As Object = NoOfAdjType(i, j);
...
Next
Next
See this MSDN article for array in VB.NET: http://msdn.microsoft.com/en-us/library/wak0wfyt.aspx
Try this,
Dim a As String = NoOfAdjType(0)(0,0)
Or use
For Each arr As Object(,) In NoOfAdjType
Next
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.