Can't find dynamically created TD in code behind - asp.net

I have created a dynamic table in my code behind which loads up on page load. I have created a button which when clicked I need to add a <div> to specific <td> in the table. However, it is not finding my <td> element using the id. What am I doing wrong?
Function CalendarRefresh(Day As Integer, MonthDays As Integer)
Dim iDay As Integer = 1
Dim TableID As Integer
Dim TDCount As Integer = 0
Dim FullTDCount As Integer = 0 '42
Dim StringHtml As New StringBuilder
Dim DaysInMonth As Integer = MonthDays
clsWork.GetUnscheduledWork()
Dim ClientName = "Terence Creighton" ' Test Replace with DB Value
Dim JobName = "Install Job"
' Top structure of table
StringHtml.Append("<table id='calendar' runatserver='server'>")
StringHtml.Append("<tr class='weekdays'>")
StringHtml.Append("<th scope='col'>Sunday</th>")
StringHtml.Append("<th scope='col'>Monday</th>")
StringHtml.Append("<th scope='col'>Tuesday</th>")
StringHtml.Append("<th scope='col'>Wednesday</th>")
StringHtml.Append("<th scope='col'>Thursday</th>")
StringHtml.Append("<th scope='col'>Friday</th>")
StringHtml.Append("<th scope='col'>Saturday</th>")
StringHtml.Append("</tr>")
StringHtml.Append("<tr Class='days'>")
If Day > 1 Then
Do While iDay < (Day)
' add Previous month style
StringHtml.Append("<td class='day other-month'>")
StringHtml.Append("</td>")
iDay = iDay + 1
TDCount = TDCount + 1
FullTDCount = FullTDCount + 1
Loop
End If
For i As Integer = 1 To DaysInMonth
If TDCount = 7 Then
StringHtml.Append("</tr>")
StringHtml.Append("<tr class='days'>")
TDCount = 0
FullTDCount = FullTDCount + 1
i = i - 1
Else
StringHtml.Append("<td class='day' ")
StringHtml.Append("id='")
StringHtml.Append(i)
StringHtml.Append("' Runat='server'>")
StringHtml.Append("<div class='date'>")
StringHtml.Append(i)
StringHtml.Append("</div>")
'StringHtml.Append("<div id='")
'StringHtml.Append(i)
'StringHtml.Append("' Runat='server'>")
'StringHtml.Append("<div Class='panel panel-primary' draggable='true'>")
'StringHtml.Append("<div Class='panel-heading'>")
'StringHtml.Append(ClientName)
'StringHtml.Append("</div>")
'StringHtml.Append("<div Class='panel-body'>")
'StringHtml.Append(JobName)
'StringHtml.Append("</div>")
'StringHtml.Append("</div>")
StringHtml.Append("</div>")
StringHtml.Append("</td>")
TDCount = TDCount + 1
FullTDCount = FullTDCount + 1
End If
Next
StringHtml.Append("</tr>")
StringHtml.Append("</table>")
Return StringHtml.ToString
End Function
Public Sub ScheduledJobs()
Dim StringHtml As New StringBuilder
Dim ClientName As String
Dim JobName As String
Dim Work = clsWork.GetUnscheduledWork()
For Each i As Integer In Work.Rows.Count
ClientName = Work.Rows(i).Items("ClientName").ToString
JobName = Work.Rows(i).Items("JobName").ToString
ID = i.ToString
StringHtml.Append("<div class='panel panel-primary' draggable='true' ondragstart='OnDragStart' ondrop='OnDrop' ")
StringHtml.Append("id='")
StringHtml.Append(ID)
StringHtml.Append("'>")
StringHtml.Append("<div class='panel-heading'>")
StringHtml.Append(ClientName)
StringHtml.Append("</div>")
StringHtml.Append("<div class='panel-body'>")
StringHtml.Append(JobName)
StringHtml.Append("</div>")
Next
Dim MyTable As HtmlTable = Page.FindControl("calendar")
Dim MyCell As HtmlTableCell
MyCell.ID = "19"
If MyCell Is Nothing Then
messageResponse = "Tablecell not found"
Else
MyCell.InnerHtml = StringHtml.ToString
End If
End Sub
Private Sub cmdLoadJobs_ServerClick(sender As Object, e As EventArgs) Handles cmdTry.ServerClick
ScheduledJobs()
End Sub
I am expecting find the td with the ID and add the html string in the ("td Element").innerhtml. I have tried various combinations of findcontrol but all turns up empty

You have to create real dynamic controls. Here a very basic example of how to interact with a dynamically created table.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//do not create dynamic control in an ispostback check
}
//create some table and it's rows and cells. note the assignent of an ID
Table table = new Table()
{
ID = "MyTable1"
};
TableRow row = new TableRow()
{
ID = "MyRow1"
};
TableCell cell = new TableCell()
{
ID = "MyCell1",
Text = "My 1st cell"
};
//add the cell to the row
row.Controls.Add(cell);
//add the row to the table
table.Controls.Add(row);
//add the table to the page
PlaceHolder1.Controls.Add(table);
}
protected void Button1_Click(object sender, EventArgs e)
{
//use findcontrol to locate the cell
TableCell cell = PlaceHolder1.FindControl("MyCell1") as TableCell;
//interact with it
cell.Text = "Cell Found!";
}

I see this:
StringHtml.Append("<table id='calendar' runatserver='server'>")
While it's certainly fine to push raw html to a page in the browser by building an html string, you cannot create server controls this way. You won't be able to access anything in that html from your code behind. The runat='server' part is first of all keyed wrong, but would be worthless even if written correctly. By the time you're in the Page_Load event, everything that looks for the runat='server' attribute has already finished.

Related

How do I get the value of a multiple dynamically generated dropdownlist?

I'm doing a small website for school and I got stuck on this problem. How can I get the value of each dropdownlist? The dropdownlist are dynamically generated by code. I did the same with the textboxes and it works perfectly, but with the values of the dropdownlists doesn't work, I mean, I don't get the values back. What should I do?
Partial Class Opties
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim aantalMensen As Integer = CInt(Session("aantalVolwassenen")) + CInt(Session("aantalKinderen")) + CInt(Session("aantalBabys"))
Session("aantalMensen") = CStr(aantalMensen)
For x As Integer = 1 To aantalMensen
'Passagiers info
Dim aanhef As New DropDownList()
Dim aanhefSelectie As ListItem
aanhefSelectie = New ListItem("Dhr.", "Dhr.")
aanhef.Items.Add(aanhefSelectie)
aanhefSelectie = New ListItem("Mevr.", "Mevr.")
aanhef.Items.Add(aanhefSelectie)
Dim voornaam As New TextBox With {.ID = "txtVoornaam" & x}
Dim achternaam As New TextBox With {.ID = "txtAchternaam" & x}
Dim lt As New Literal()
Dim Endlt As New Literal()
Dim space As New Literal()
lt.Text = "<p>Persoon " + CStr(x) + ":"
Endlt.Text = "</p> "
space.Text = "<br />"
gegevensPassagiers.Controls.Add(lt)
gegevensPassagiers.Controls.Add(aanhef)
gegevensPassagiers.Controls.Add(voornaam)
gegevensPassagiers.Controls.Add(achternaam)
gegevensPassagiers.Controls.Add(Endlt)
gegevensPassagiers.Controls.Add(space)
Next
For i As Integer = 1 To aantalMensen
'Bagage DropDownlist
Dim aantalKG As New DropDownList With {.ID = "ddlBagage" & i}
Dim KGselectie As ListItem
KGselectie = New ListItem("Geen", "Geen")
aantalKG.Items.Add(KGselectie)
KGselectie = New ListItem("15kg", "15kg")
aantalKG.Items.Add(KGselectie)
KGselectie = New ListItem("25kg", "25kg")
aantalKG.Items.Add(KGselectie)
KGselectie = New ListItem("35kg", "35kg")
aantalKG.Items.Add(KGselectie)
aantalKG.AutoPostBack = True
Dim lt As New Literal()
Dim Endlt As New Literal()
Dim space As New Literal()
lt.Text = "<p>Persoon " + CStr(i) + ":"
Endlt.Text = "</p> "
space.Text = "<br />"
bagageDIV.Controls.Add(lt)
bagageDIV.Controls.Add(aantalKG)
bagageDIV.Controls.Add(Endlt)
bagageDIV.Controls.Add(space)
Next
Dim index As Integer = 1
If IsPostBack Then
For Each key As String In Request.Form.Keys
If key.Contains("txtVoornaam") Then
Session("Voornaam" & index) = CType(Request.Form(key), String)
index += 1
End If
If key.Contains("txtFamilienaam") Then
Session("Familienaam" & index) = CType(Request.Form(key), String)
index += 1
End If
If key.Contains("ddlBagage") Then
Session("Bagage" & index) = CType(Request.Form(key), String)
index += 1
End If
Next
End If
End Sub
You can use JavaScript for get selected value of dropdownlists.
for example:
var e = document.getElementById("aanhef ");
var Selectedvalue = e.options[e.selectedIndex].value;
Well, after testing some methodes and attributes and other stuff.... I found an easy solution for my problem (also thanks for helping #MaCron).
Here is the code:
For Each aantalKG As DropDownList In bagageDIV.Controls.OfType(Of DropDownList)()
Session("Bagage" & index) = aantalKG.SelectedValue
index += 1
Next

Reset pagesize for each record iText

I am trying to reset the pagesize of each record in pdf, which is the total page
(1 of pagesize
2 of pagesize.......)
The 1st blockcode work for 1 single record but then when it come to multiple record it showed:
1 of 0 //1st record
2 of 0
1 of 0 //2nd record
.......
I think there is something to do with document.setPageSize() but it is boolean and belong to Rectangle.
Please help me solve this problem.
Thank.
Public Overrides Sub onEndPage(ByVal writer As PdfWriter, ByVal document As Document)
Dim page As Rectangle = document.getPageSize()
Dim cb As PdfContentByte = writer.getDirectContent()
Dim arialbasefont As BaseFont = arial.getBaseFont
Dim pg As Rectangle = document.getPageSize()
Dim pageNumberText As String = "Page " & writer.getPageNumber() & " of "
Dim timeStampText As String = Now.ToString
Dim pageNumberTextLength As Double = arialbasefont.getWidthPoint(pageNumberText, footerFontSize)
Dim timeStampTextLength As Double = arialbasefont.getWidthPoint(timeStampText, footerFontSize)
Dim pageNumberTextLeft As Double = 20
Dim templateLeft As Double = pageNumberTextLeft + pageNumberTextLength
Dim pageNumberTextBottom As Double = 5 + footerFontSize
cb.beginText()
cb.setFontAndSize(arialbasefont, footerFontSize)
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, pageNumberText, pageNumberTextLeft, pageNumberTextBottom, 0)
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, Now, pg.urx - (timeStampTextLength + 20), pageNumberTextBottom, 0)
cb.endText()
cb.addTemplate(tpl, templateLeft, pageNumberTextBottom)
End Sub
For Each ProjectID In array
Dim rptRequestReportObj As New rptRequestReport2
rptRequestReportObj.Report(document, ProjectID)
document.newPage()
document.setPageCount(1)
Next ProjectID

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

ASP.NET DataSet loses data?

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

Resources