Use property value based on string - asp.net

I have a search filter that goes through the list of customers that I have, and depending on whether the string contains the value or not, returns the list that satisfies the condition. Right now it checks the company property in the condition, but I'd like it to be able to check any property that's given in the method (customerDetail is the property name in this function). How can I pass the string property and make it work with this statement?
If(oListOfCustomers.Item(iIndex).Company.ToString.Trim.Contains(sStringContains) = True) Then
For clarification, I want something along the lines of:
If(oListOfCustomers.Item(iIndex).customerDetail.ToString.Trim.Contains(sStringContains) = True) Then
Here's the function:
Public Shared Function GetContains(ByVal sStringContains As String, ByVal customerDetail As String, ByVal oListOfCustomers As List(Of Customer))
Dim oCustomerData As New CustomerData
Dim oNewListOfCustomers As New List(Of Customer)
Dim iIndex As Integer
Dim oCustomer As Customer
'Property Names: Company, Contact, City, State, Country, Zip, Status
'Check for all properties. It works though.
If IsNothing(oListOfCustomers) = False AndAlso oListOfCustomers.Count > 0 Then
For iIndex = 0 To oListOfCustomers.Count - 1
If (oListOfCustomers.Item(iIndex).Company.ToString.Trim.Contains(sStringContains) = True) Then
oCustomer = New Customer(oListOfCustomers.Item(iIndex).Company, oListOfCustomers.Item(iIndex).Contact, oListOfCustomers.Item(iIndex).Address1, oListOfCustomers.Item(iIndex).Address2, _
oListOfCustomers.Item(iIndex).City, oListOfCustomers.Item(iIndex).State, oListOfCustomers.Item(iIndex).Country, oListOfCustomers.Item(iIndex).Zip, _
oListOfCustomers.Item(iIndex).Zip4, oListOfCustomers.Item(iIndex).Email, oListOfCustomers.Item(iIndex).Phone, oListOfCustomers.Item(iIndex).Status, _
oListOfCustomers.Item(iIndex).MasterContactID)
oNewListOfCustomers.Add(oCustomer)
End If
Next
End If
Return oNewListOfCustomers
End Function

You could use reflection and PropertyInfo.GetValue. Try (untested):
Imports System.Reflection
Public Shared Function GetContains(ByVal sStringContains As String, ByVal customerDetail As String, ByVal oListOfCustomers As List(Of Customer))
Dim oCustomerData As New CustomerData
Dim oNewListOfCustomers As New List(Of Customer)
Dim iIndex As Integer
Dim oCustomer As Customer
Dim propertyInfo As PropertyInfo
'Property Names: Company, Contact, City, State, Country, Zip, Status
'Get PropertyInfo for customerDetail-property
propertyInfo = GetType(Customer).GetProperty(customerDetail)
'Check for all properties. It works though.
If IsNothing(oListOfCustomers) = False AndAlso oListOfCustomers.Count > 0 Then
For iIndex = 0 To oListOfCustomers.Count - 1
If (propertyInfo.GetValue(oListOfCustomers.Item(iIndex)).ToString.Trim.Contains(sStringContains) = True) Then
oCustomer = New Customer(oListOfCustomers.Item(iIndex).Company, oListOfCustomers.Item(iIndex).Contact, oListOfCustomers.Item(iIndex).Address1, oListOfCustomers.Item(iIndex).Address2,
oListOfCustomers.Item(iIndex).City, oListOfCustomers.Item(iIndex).State, oListOfCustomers.Item(iIndex).Country, oListOfCustomers.Item(iIndex).Zip,
oListOfCustomers.Item(iIndex).Zip4, oListOfCustomers.Item(iIndex).Email, oListOfCustomers.Item(iIndex).Phone, oListOfCustomers.Item(iIndex).Status,
oListOfCustomers.Item(iIndex).MasterContactID)
oNewListOfCustomers.Add(oCustomer)
End If
Next
End If
Return oNewListOfCustomers
End Function

Related

How to separate group of line series in different panes in DevExpress BootstrapChart?

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

How do i get access to checkboxes dynamically generated in loop

I am new to asp.net and vb.net programming and i can't find a answer to my problem. I have dynamically generated checkboxes in a loop at runtime within a sub.
This is a grid scheduler program that displays selected day's and selected hours from a location which is selected from a different page. I want to acces the checkboxes by id but i cant get acces to them because the checkboxes are not declared at class level.
Can anyone help me please, i have searched all day long for a solution. I Prefer VB but C# is fine also.
Below is my codebehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindLocationDayTime()
End If
End Sub
Public Sub BindLocationDayTime()
Dim ID As Integer
Dim Name As String
Dim Day As Integer
Dim Time As Integer
Dim StartDate As DateTime
Dim EndDate As DateTime
Dim Locations As SqlDataReader = GetLocations()
For Each Item In Locations
Dim LRow As New TableRow()
Dim LCell As New TableCell()
LCell.Text = Locations.Item("Name")
LCell.Attributes.Add("class", "LocationHeader")
LCell.Attributes.Add("colspan", "5")
LRow.Cells.Add(LCell)
LocationData.Rows.Add(LRow)
Dim Location As SqlDataReader = GetLocation(Convert.ToInt32(Locations.Item("Id")))
While Location.Read()
Name = Location("Name").ToString()
StartDate = Location("StartDate")
EndDate = Location("EndDate")
End While
Dim dtfi As Globalization.DateTimeFormatInfo = Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat
Dim tRowCount As Integer = 0
Do While StartDate <= EndDate
Dim LocationDayTime As SqlDataReader = GetPlayDayTime(Convert.ToInt32(Locations.Item("Id")))
For Each row In LocationDayTime
Day = LocationDayTime.Item("DayID")
Time = LocationDayTime.Item("TimeID")
ID = Locations.Item("Id")
If Day = 1 Then
If StartDate.DayOfWeek = DayOfWeek.Monday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
ElseIf Day = 2 Then
If StartDate.DayOfWeek = DayOfWeek.Tuesday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
ElseIf Day = 3 Then
If StartDate.DayOfWeek = DayOfWeek.Wednesday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
ElseIf Day = 4 Then
If StartDate.DayOfWeek = DayOfWeek.Thursday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
ElseIf Day = 5 Then
If StartDate.DayOfWeek = DayOfWeek.Friday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
End If
Next
StartDate = StartDate.AddDays(1)
Loop
Next
End Sub
Public Sub BindDays(ByVal StartDate As DateTime, ByVal ID As Integer, ByVal tRowCount As Integer, ByVal Time As Integer)
Dim dtfi As Globalization.DateTimeFormatInfo = Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat
Dim tRow As New TableRow()
Dim Cell1 As New TableCell()
Dim strDayOfWeek As String = dtfi.GetDayName(StartDate.DayOfWeek)
Cell1.Text = UppercaseFirstLetter(strDayOfWeek & " ") & (StartDate.Date.ToShortDateString & " om ") & (Time & "uur ")
Cell1.Attributes.Add("class", "MemberCell")
tRow.Cells.Add(Cell1)
Dim Cell2 As New TableCell()
Dim cbAvailible As New CheckBox()
cbAvailible.ID = (StartDate.Date) & "," & (Time)
cbAvailible.Checked = False
Cell2.Controls.Add(cbAvailible)
tRow.Cells.Add(Cell2)
Dim Cell3 As New TableCell()
Dim Label As New Label()
Label.Text = ("(Op deze datum ben ik verhinderd)")
Cell3.Controls.Add(Label)
tRow.Cells.Add(Cell3)
If tRowCount Mod 2 Then
tRow.Attributes.Add("class", "alternatingItemStyle")
Else
tRow.Attributes.Add("class", "itemStyle")
End If
LocationData.Rows.Add(tRow)
End Sub
#End Region
#Region " Events "
Private Sub Insert_Click(sender As Object, e As EventArgs) Handles Insert.Click
' I want to get here al the checkbox id and insert the values to a databse
End Sub
End Region
Solution 1 - Using recursive control search
I have done something similar with a dynamically generated form with a variable number of controls (textboxes, dropdowns, and checkboxes) and control state being data driven. I would not be looking to tie into the events of the generated controls (would require a jerky postback) but have a "Save" button and from that event do a recursive GetChildControls function that starts from the container holding your dynamic controls. Have a convention when assigning an id for each dynamic control so when you later loop back through them you can know which control is related to which record.
The recursive function:
Public Class ControlUtils
Shared Function GetChildControls(ByVal ctrl As Control, Optional ByVal ctrlType As Type = Nothing) As Control()
Dim controls As New ArrayList()
For Each c As Control In ctrl.Controls
' add this control and all its nested controls
If ctrlType Is Nothing OrElse ctrlType.IsAssignableFrom(c.GetType()) Then
controls.Add(c)
controls.AddRange(GetChildControls(c))
End If
Next
' return the result as an array of Controls
Return DirectCast(controls.ToArray(GetType(Control)), Control())
End Function
End Class
Basic idea with a contrived dynamic form...
A class to represent the database info:
Public Class Location
Public Property ID As Integer
Public Property Name As String
Public Property StartDate As Date
Public Property EndDate As Date
Shared Function GetSampleLocations() As List(Of Location)
Dim sample As New List(Of Location)
Dim loc As Location
For j = 1 To 5
loc = New Location
loc.ID = j
loc.Name = "Location " & j
loc.StartDate = Date.Today
loc.EndDate = Date.Today.AddDays(6 - j)
sample.Add(loc)
Next
Return sample
End Function
End Class
The class that has the methods to build the "form" and save its data:
Public Class LocationsDynamicForm
Dim _Locations As IEnumerable(Of Location)
Sub New(locations As IEnumerable(Of Location))
_Locations = locations
End Sub
Sub InsertEditForm(plc As PlaceHolder, setUserInput As Boolean)
'build and add controls to placeholder
Dim tbl As New Table
Dim r As TableRow
Dim c As TableCell
For Each loc As Location In _Locations
r = New TableRow
'add cell for location name
c = New TableCell
c.Controls.Add(New LiteralControl(loc.Name)) 'add plain text through literal control
r.Cells.Add(c)
'add cell for each day in the date range for current location
Dim currentDate As Date = loc.StartDate
Do Until currentDate > loc.EndDate
c = New TableCell
Dim chk As New CheckBox
chk.ID = "chkLocationDate_" & loc.ID & "_" & currentDate.Ticks
chk.Text = currentDate.ToShortDateString
If setUserInput Then
'set the check state based on current database value
Dim pretendValueCameFromDB As Boolean = True
chk.Checked = pretendValueCameFromDB
End If
c.Controls.Add(chk)
r.Cells.Add(c)
currentDate = currentDate.AddDays(1)
Loop
tbl.Rows.Add(r)
Next
plc.Controls.Add(tbl)
End Sub
Sub SaveForm(ByVal plc As PlaceHolder)
Dim ctl As Control
Dim controlIDParts() As String
Dim drp As DropDownList
Dim txt As TextBox
Dim chk As CheckBox
For Each ctl In ControlUtils.GetChildControls(plc, GetType(Control))
If ctl.GetType Is GetType(DropDownList) Then
drp = CType(ctl, DropDownList)
If drp.ID Like "drpIT_*" Then
controlIDParts = drp.ID.Split("_")
'update record...
End If
ElseIf ctl.GetType Is GetType(TextBox) Then
txt = CType(ctl, TextBox)
If txt.ID Like "txtIT_*" Then
controlIDParts = txt.ID.Split("_")
'update record...
End If
ElseIf ctl.GetType Is GetType(CheckBox) Then
chk = CType(ctl, CheckBox)
If chk.ID Like "chkLocationDate_*" Then
controlIDParts = chk.ID.Split("_")
Dim locationID = controlIDParts(1)
Dim ticks As Long = Val(controlIDParts(2))
Dim d As New Date(ticks)
'update record...
End If
End If
Next
'commit record changes...
End Sub
End Class
And its use inside the webform (assuming you have a save button and placeholder control):
Dim _Locations As List(Of Location)
Dim _LocationsForm As LocationsDynamicForm
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
_Locations = Location.GetSampleLocations()
_LocationsForm = New LocationsDynamicForm(_Locations)
_LocationsForm.InsertEditForm(plcLocations, Not Me.IsPostBack)
End Sub
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
_LocationsForm.SaveForm(plcLocations)
End Sub
Solution 2 - Use AddHandler with Dynamically added controls
This is closer to what you want, but requires a postback on each checkbox change. In your BindDays routine add these lines when you are adding the checkbox.
cbAvailible.AutoPostBack = True
AddHandler cbAvailible.CheckedChanged, AddressOf Insert_Click
You should trim the Handles keyword at the end of your sub Insert_Click signature. The Handles is nice when you have foreknowledge of the control(s) you will be handling but the controls don't exist at design time.
Private Sub Insert_Click(sender As Object, e As EventArgs)
' I want to get here al the checkbox id and insert the values to a databse
Dim chk As CheckBox = CType(sender, CheckBox)
Label1.Text = "ID = " & chk.ID & ", Checked = " & chk.Checked
End Sub
I'm not sure how you are persisting your 'LocationData' across postbacks or adding it to the web page but I was able to get a modified version of your code working.
' Global declaration inside the "Form" class.
Public Checkboxes as New List(of Checkbox)
Each time you create a "new checkbox" add it to the collection.
...
Dim cbAvailible As New CheckBox()
Checkboxes.Add(cbAvailable)
...
Later you can simply refer to the checkbox by Index.
Dim chk as boolean = Checkboxes(2).checked ' example
The other Alternative is to use a Generic.Dictionary to store the checkboxes, in that case each box can have a "Key" like a string that relates to the row or something specific.
Looping through Checkboxes.
For iQ AS integer = 0 to Checkboxes.Count -1
Dim cb as checkbox = Checkboxes(iq) ' just a way to not use long name during operations.
Dim checked as boolean = cb.checked ' ... ' do your work here
' ...
Next iQ
Odds are you will need to do the same with all your objects (per row).
The Last Index should be the same for all of them. Which should be the same as the number of rows in your table object as well.

Accessing multiple dynamic controls values

I am adding multiple controls dynamically based on a dropdownlist that the user selects. i.e. if the user selects 3 then 3 sets of the controls are added. My problem is not in adding the controls, I can add them fine, I haven't added all my code but the main parts to understand what I am doing.
Once the controls have been created, the relevant info is captured. On the Update click I need to access the values of these dynamic controls by looping through in the correct order and retrieve the values and write to the database. I can't seem to access them correctly.
Hopefully I am making sense. Any help would be appreciated. Thanks
''Loop through first set of controls and get values and then the next set etc..
Dim Description as string = ''Get Textbox value
Dim Type as string = ''Get RadComboBox value
Dim XFieldName as string = ''Get RadComboBox value
Dim Colour as string = ''Get RadColorPicker value
Below is my Code:
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RecreateControlsTxt("txt", "TextBox")
RecreateControlsChart("comboChart", "RadComboBox")
RecreateControls("combo", "RadComboBox")
RecreateControlsCP("cp", "RadColorPicker")
End Sub
Protected Sub AddControls_Click(sender As Object, e As EventArgs) Handles AddControls.Click
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateTextbox("txt-" & Convert.ToString(i + 1))
Next
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateComboChart("comboChart-" & Convert.ToString(i + 1))
Next
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateComboField("combo-" & Convert.ToString(i + 1))
Next
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateColourPicker("cp-" & Convert.ToString(i + 1))
Next
End Sub
Private Sub CreateTextbox(ByVal ID As String)
Dim txt As New TextBox()
txt.ID = ID
txt.Height = 20
Me.divDesc.Controls.Add(txt)
End Sub
Private Sub CreateComboField(ByVal ID As String)
Dim combo As New RadComboBox()
combo.ID = ID
combo.DataSource = Me.odsChartsSeriesField
combo.DataTextField = "FieldNames"
combo.DataValueField = "FieldNames"
combo.DataBind()
Me.divField.Controls.Add(combo)
End Sub
Private Sub CreateComboChart(ByVal ID As String)
Dim comboChart As New RadComboBox()
comboChart.ID = ID
Dim item1 As New RadComboBoxItem()
item1.Text = "Line"
item1.Value = "smoothedLine"
item1.ImageUrl = ("Images/linechart.png")
comboChart.Items.Add(item1)
Dim item2 As New RadComboBoxItem()
item2.Text = "Column"
item2.Value = "column"
item2.ImageUrl = ("Images/bar chart.png")
comboChart.Items.Add(item2)
Dim item3 As New RadComboBoxItem()
item3.Text = "Pie"
item3.Value = "pie"
item3.ImageUrl = ("Images/pie chart.jpg")
comboChart.Items.Add(item3)
Me.divChart.Controls.Add(comboChart)
End Sub
Private Sub CreateColourPicker(ByVal ID As String)
Dim cp As New RadColorPicker()
cp.ID = ID
cp.ShowIcon = True
cp.Style("padding-top") = "1px"
cp.CssClass = "CustomHeight"
Me.divCol.Controls.Add(cp)
End Sub
Protected Sub Update_Click(sender As Object, e As EventArgs) Handles Update.Click
Try
Dim alltxt = divDesc.Controls.OfType(Of TextBox)()
Dim allcomboChart = divChart.Controls.OfType(Of RadComboBox)()
Dim allcomboField = divField.Controls.OfType(Of RadComboBox)()
Dim allcp = divCol.Controls.OfType(Of RadColorPicker)()
''Loop through first set of controls and get values and then the next etc..
Dim Description as string = ''Get Textbox value
Dim Type as string = ''Get RadComboBox value
Dim XFieldName as string = ''Get RadComboBox value
Dim Colour as string = ''Get RadColorPicker value
If Page.IsValid Then
Dim da As New dsSVTableAdapters.Chart
Dim Result As String = da.Series(60, Description, Type, Colour, "YFieldName", XFieldName)
End If
Catch ex As Exception
lblResult.Text = ex.Message
End Try
End Sub
You have a repeated set of controls. Therefore you need a corresponding repeated set of variables that store these values.
I suggest creating a class where you can store a variable (or property) set.
Public Class ControlSet
Public Property Description As String
Public Property Type As String
Public Property XFieldName As String
Public Property Colour As String
End Class
Create an array that holds these values
Dim Values = New ControlSet(ddlFieldNames.SelectedIndex) {}
And retrieve the values in a loop
For i As Integer = 0 To Values.Length - 1
Values(i).Description = CType(divDesc.FindControl("txt-" & Convert.ToString(i + 1)), TextBox).Text
Values(i).Type = CType(divChart.FindControl("comboChart-" & Convert.ToString(i + 1)), RadComboBox).SelectedValue
Values(i).XFieldName = ...
...
Next
Also use the ID of the control; this helps to avoid confusion in case you have several controls of the same type.
you can use .FindControl(string id) method, and you should keep the controls count in your view state or session:
Protected Sub Update_Click(sender As Object, e As EventArgs) Handles Update.Click
Try
''Loop through first set of controls and get values and then the next etc..
For i As Integer = 0 To controlsCount - 1
Dim Description as string = ((TextBox)divDesc.FindControl("txt-" & Convert.ToString(i + 1))).Text ''Get Textbox value
Dim Type as string = ((RadComboBox)divChart.FindControl("comboChart-" & Convert.ToString(i + 1))).SelectedValue ''Get RadComboBox value
Dim XFieldName as string = ((RadComboBox)divField.FindControl("combo-" & Convert.ToString(i + 1))).SelectedValue ''Get RadComboBox value
Dim Colour as string = ((RadColorPicker)divField.FindControl("cp-" & Convert.ToString(i + 1))).SelectedValue ''Get RadColorPicker value
If Page.IsValid Then
Dim da As New dsSVTableAdapters.Chart
Dim Result As String = da.Series(60, Description, Type, Colour, "YFieldName", XFieldName)
Next
End If
Catch ex As Exception
lblResult.Text = ex.Message
End Try
End Sub

LINQ - Putting result in a dictionary(Of String, Integer), where the integer must be 0

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);
}

VB.NET SQL UPDATE command returns error "Argument not specified for parameter."

My update query (built from the dataset wizard) does not update anything and I am not receiving any errors.
I have checked my parameter (param1) and it is passing correctly.
When I debug my immediate window updateta.insertquery() tells me this:
Argument not specified for parameter 'StockNum' of 'Public Overridable Function UpdateQuery(StockNum As String, Year As String, Make As String, Model As String, Color As String, Location As String, TiresNeeded As Boolean, StockIn As Date?, SvcRONum As String, UCIStartDate As Date?, UCIEstCompleteDate As Date?, Repairs As Boolean, CollisionRONum As String, Detail As Date?, Other As String, OnLot As Boolean, OffProperty As Boolean, Sold As Boolean, Original_RecNum As Integer) As Integer'.
why are there question marks after some of the dates??
here is my code vb code. Any ideas?? Thanks!!
Protected Sub SubmitBTN_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdateBTN.Click
Dim updateta As New DataSet1TableAdapters.MasterTableAdapter
updateta.UpdateQuery(StockNumTxt.Text, YearTxt.Text, MakeTxt.Text, ModelTxt.Text, ColorTxt.Text, LocationDropDownList.SelectedValue, TiresCHK.Checked, StockInDateTxt.Text, SrvcROnumTxt.Text, UCIStartDateTxt.Text, UCIEstComDateTXT.Text, RepairsCheckBX.Checked, CollisionRONumTXT.Text, DetailTXTbox.Text, OtherTxt.Text, OnLotCheckBX.Checked, OffPropertyCheckBX.Checked, SoldCheckBX.Checked, Request.QueryString("param1"))
Response.Redirect("success.aspx")
End Sub
Function myCStr(ByVal test As Object) As String
If isdbnull(test) Then
Return ("")
Else
Return CStr(test)
End If
End Function
Public Shared Function IsDBNull( _
ByVal value As Object _
) As Boolean
Return DBNull.Value.Equals(value)
End Function
Private Sub getData(ByVal user As String)
'declare variables to fill
Dim stock As String, make As String, color As String, stockin As Date, ucistart As Date, repairs As Boolean, _
tires As Boolean, onlot As Boolean, sold As Boolean, year As Boolean, model As String, location As String, srvcRO As String, ucicompldate As Date, _
collRO As String, other As String, offprop As Boolean, detail As Date
Dim dt As New DataTable()
Dim connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jason\Desktop\UsedCarProductionSched\UsedCars.accdb;Persist Security Info=False;")
connection.Open()
Dim sqlcmd As String = "SELECT * from Master WHERE RecNum = #recnum"
Dim FileCommand3 As New OleDb.OleDbCommand(sqlcmd, connection)
FileCommand3.Parameters.AddWithValue("#recnum", user)
Dim Reader3 As OleDb.OleDbDataReader = FileCommand3.ExecuteReader()
If Reader3.Read Then
stock = myCStr(Reader3("StockNum"))
make = myCStr(Reader3("Make"))
color = myCStr(Reader3("Color"))
stockin = IIf(Reader3("stockin") Is DBNull.Value, Nothing, Reader3("stockin"))
ucistart = IIf(Reader3("ucistartdate") Is DBNull.Value, Nothing, Reader3("ucistartdate"))
repairs = Reader3("Repairs")
tires = Reader3("tiresneeded")
onlot = Reader3("onlot")
sold = Reader3("sold")
year = myCStr(Reader3("year"))
model = myCStr(Reader3("model"))
location = myCStr(Reader3("location"))
srvcRO = myCStr(Reader3("svcROnum"))
ucicompldate = IIf(Reader3("uciestcompletedate") Is DBNull.Value, Nothing, Reader3("uciestcompletedate"))
collRO = myCStr(Reader3("collisionROnum"))
other = myCStr(Reader3("other"))
offprop = Reader3("offProperty")
detail = IIf(Reader3("detail") Is DBNull.Value, Nothing, Reader3("detail"))
End If
connection.Close()
If detail <> Nothing Then
DetailTXTbox.Text = detail.ToString("M/dd/yyyy")
Else : DetailTXTbox.Text = ""
End If
If ucicompldate <> Nothing Then
UCIEstComDateTXT.Text = ucicompldate.ToString("MM/dd/yyyy")
Else : UCIEstComDateTXT.Text = ""
End If
If stockin <> Nothing Then
StockInDateTxt.Text = stockin.ToString("MM/dd/yyyy")
Else : StockInDateTxt.Text = ""
End If
If ucistart <> Nothing Then
UCIStartDateTxt.Text = ucistart.ToString("M/dd/yyyy")
Else : UCIStartDateTxt.Text = ""
End If
StockNumTxt.Text = stock
MakeTxt.Text = make
ColorTxt.Text = color
RepairsCheckBX.Checked = repairs
TiresCHK.Checked = tires
OnLotCheckBX.Checked = onlot
SoldCheckBX.Checked = sold
YearTxt.Text = year
ModelTxt.Text = model
If location <> Nothing Then
LocationDropDownList.SelectedValue = location
End If
SrvcROnumTxt.Text = srvcRO
CollisionRONumTXT.Text = collRO
OtherTxt.Text = other
OffPropertyCheckBX.Checked = offprop
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
getData(Request.QueryString("param1"))
End Sub
As for the question marks after Date?, I'm pretty sure that indicates the Date is a nullable field. Does your database table allow NULL on those fields?
When you put a debug break point right before your updateta.UpdateQuery, are you certain StockNumTxt.Text has a value?
Access like # signs around dates. Have you tried putting # signs around your date values?

Resources