ASP.NET DataSet loses data? - asp.net

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

Related

get values of dynamic checkboxes

I am dynamically creating checkboxes in VB.Net and an .aspx page, based on values in my db. I'm placing them in a two column table for ease of alignment. this part works fine.
Private Async Function InitForEditAsync() As Task
Dim docList = Await GetLoanApplicationConfigurationDocs()
Dim row = New HtmlTableRow()
Dim cell = New HtmlTableCell()
Dim i = 0
For Each doc In docList
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = i Mod 2
chkBox.ID = "chkDocId" + doc.Id.ToString
lbl.Text = doc.DisplayName
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
If remainder <> 0 OrElse i = docList.Count() - 1 Then
tblEdit.Rows.Add(row)
row = New HtmlTableRow()
End If
i += 1
Next
End Function
Now I need to retrieve the values without knowing the id's but am not having any luck. I tried this:
For Each chkBox As HtmlInputCheckBox In pnlEdit.Controls.OfType(Of HtmlInputCheckBox)
but the checkboxes are not returned in the list of controls. The table is, but there are no rows in the table object when I explored it in the control collection and when I tried this:
For Each row As HtmlTableRow In tblEdit.Rows.OfType(Of HtmlTableRow)
If it will help, here is a Snip of the UI and the HTML that is created:
Any suggestions are appreciated. Thanks in advance.
Based on some ideas I got from another site, I'm going to rewrite this using the asp:CheckBoxList. apparently it binds like a datagrid and you can enumerate through it. Seems like what i need.
UPDATE: Everything I posted to start was resolved with five lines of code! "cblDocList is my asp CheckboxList and docList is my ienumerable of objects.
cblDocList.RepeatColumns = 2
cblDocList.DataSource = docList
cblDocList.DataTextField = "DisplayName"
cblDocList.DataValueField = "Id"
cblDocList.DataBind()
It’s something you can do through a loop for each row and each cell or using Linq to have only cells that have controls of type HtmlInputCheckBox inside.
I have simplified your code to be able run that here also shows you an example to achieve your task. Obviously you must change following your exigences .
Hope I well understood :)
Dim tblEdit As New HtmlTable
For k As Integer = 0 To 10
Dim cell = New HtmlTableCell()
Dim row = New HtmlTableRow()
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = k Mod 2
chkBox.ID = "chkDocId_" + k.ToString
chkBox.Checked = remainder = 0
lbl.Text = "Text indicator of CheckBox nr:" + k.ToString
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
tblEdit.Rows.Add(row)
Next
Dim checkBoxes As IEnumerable(Of HtmlInputCheckBox) =
(From mRow In tblEdit.Rows).Select(Function(mr)
Dim cb = (From cc In CType(mr, HtmlTableRow).Cells
Where CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox).Count > 0
Select CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox)()(0)).FirstOrDefault
Return CType(cb, HtmlInputCheckBox)
End Function).ToList
For Each checkBox In checkBoxes
Debug.WriteLine("CheckBox ID: {0} Checked: {1} ", checkBox.ID, checkBox.Checked)
Next

Add new Column to existing Dataview

I wanted to add New Column to the Existing Dataview as shown in below image. the new column should have value 1 or 0 base upon the value of DocumentType,HouseOrigin and StorageDate. basically i am checking if Document type and HouseOrigin is same then put 0 for the latest storageDate and put 1 for other row.
Hope below image will help to understand.
How i will do it ? TIA.
this is how i am get it. Hope that helps !!
If DetailsView.Count > 0 Then
Dim col As DataColumn = New DataColumn("DisableFlag", GetType(Boolean))
col.DefaultValue = True
DetailsView.Table.Columns.Add(New DataColumn("DisableFlag", GetType(Boolean)))
Dim LocalDV As DataView = DetailsView
Dim result As List(Of DataTable) = DetailsView.Table.AsEnumerable.GroupBy(Function(row) row.Field(Of String)("DocumentType")).[Select](Function(g) g.CopyToDataTable()).ToList()
For Each rowView As DataRowView In DetailsView
Dim row As DataRow = rowView.Row
For Each DivByDocTypedt As DataTable In result
Dim maxDate As Object = DivByDocTypedt.Compute("MAX(StorageDate)", Nothing)
For Each DivByDocTyperow As DataRow In DivByDocTypedt.Rows
If (DivByDocTyperow.Item("Guid") = row.Item("Guid")) Then
If (maxDate = row.Item("StorageDate")) Then
row.SetField("DisableFlag", False)
Else
row.SetField("DisableFlag", True)
End If
End If
Next '' DivByDocTyperow
Next ''DivByDocTypedt
Next ''rowView of DetailsView

getting values from a selected item in a dropdownlist in a table cell that was dynamically created in a table in vb code behind

I have created a table dynamically on an asp.net page by creating the rows based of off the number of rows in a dataset from a SQL database. I used a for loop to create my rows and cells with the populated dropdownlists in the page_load() function. My table is created exactly how it needs to be, but I need to get the selected item text for each cell in every row to store back to a database table upon clicking the submit button. I initially have a placeholder on my asp page and replace it with the created table on load. For some reason, when i try to use
For Each r As TableRow In LineupTable.Rows
msgbox(EmployeeDDL.SelectedItem.Text)
Next r
it gives me a null value error for employeeddl.selecteditem.text.
This is how I generate my table.
'Dynamically create table rows and cells and populate them with the proper controls and/or information
Dim numrows As Integer = dtEQP.Rows.Count
Dim numcells As Integer = 6
Dim j As Integer
For j = 0 To numrows - 1
r = New TableRow()
c1 = New TableCell() With {.Width = 300}
c1.Controls.Add(New LiteralControl(dtEQP.Rows(j).ItemArray(0)))
r.Cells.Add(c1)
c2 = New TableCell() With {.Width = 200}
Dim EmployeeDDL As New DropDownList()
EmployeeDDL.DataSource = dsEMP
EmployeeDDL.DataTextField = "FirstName"
EmployeeDDL.DataValueField = "ID"
EmployeeDDL.DataBind()
EmployeeDDL.Items.Insert(0, New ListItem("", "-1"))
c2.Controls.Add(EmployeeDDL)
r.Cells.Add(c2)
c3 = New TableCell() With {.Width = 180}
Dim CodeDDL As New DropDownList()
CodeDDL.Items.Add("0-Running")
CodeDDL.Items.Add("99-Idle")
CodeDDL.Items.Add("60-Down")
CodeDDL.Items.Add("1-Weather")
CodeDDL.SelectedValue = "99-Idle"
c3.Controls.Add(CodeDDL)
r.Cells.Add(c3)
c4 = New TableCell() With {.Width = 100}
Dim RideDDL1 As New DropDownList()
RideDDL1.DataSource = dsRide
RideDDL1.DataTextField = "Ridename"
RideDDL1.DataValueField = "RideID"
RideDDL1.DataBind()
RideDDL1.Items.Insert(0, New ListItem("", "-1"))
c4.Controls.Add(RideDDL1)
r.Cells.Add(c4)
c5 = New TableCell() With {.Width = 200}
Dim OTddl1 As New DropDownList()
OTddl1.DataSource = dsEMP2
OTddl1.DataTextField = "FirstName"
OTddl1.DataValueField = "ID"
OTddl1.DataBind()
OTddl1.Items.Insert(0, New ListItem("", "-1"))
c5.Controls.Add(OTddl1)
r.Cells.Add(c5)
c6 = New TableCell() With {.Width = 350}
Dim CommentsTxtBx As New TextBox()
c6.Controls.Add(CommentsTxtBx)
r.Cells.Add(c6)
LineupTable.Rows.Add(r)
Next j
Any ideas on how I should be retrieving this value in my on click subroutine to get what was actually selected?
First when you add the DropDownList, give it an ID (use your cursor variable to avoid having a duplicate ID):
EmployeeDDL.ID = "EmployeeDDL" & j.ToString()
Secondly, since the DropDownList was dynamically added you need to use FindControl to get an instance of it. Also, make sure SelectedItem is not null/nothing.
Dim intCursor As Integer = 0
For Each r As TableRow In LineupTable.Rows
Dim ddlTarget As DropDownList = Cast(r.Cells(1).FindControl("EmployeeDDL" & intCursor.ToString()), DropDownList)
If Not ddlTarget.SelectedItem Is Nothing Then
Dim strValue = ddlTarget.SelectedItem.Text
End If
intCursor += 1
Next r

Adding Rows dynamically to GridView in ASP.NET

I use the following code for adding Rows dynamically to GridView in ASP.NET.
ViewState("CourseFeesDetails") = dsGetStudentCourseFeesDetail
If ViewState("CourseFeesDetails") IsNot Nothing Then
Dim dtCourseTable As New DataTable
dtCourseTable = CType(ViewState("CourseFeesDetails"), DataTable)
Dim drCurrentRow As DataRow = Nothing
Dim txtFeesAmt As New System.Web.UI.WebControls.TextBox
If dtCourseTable.Rows.Count > 0 Then
For i = 1 To nNoOfInstallments
drCurrentRow = dtCourseTable.NewRow()
i = i + 1
dtCourseTable.Rows.Add(drCurrentRow)
Next
ViewState("CourseFeesDetails") = dtCourseTable
gvCourseFeeDisplay.DataSource = dtCourseTable
gvCourseFeeDisplay.DataBind()
End If
End If
It does add the number of rows, but adds 1 extra. What should I do?

Dynamic tables with hyperlinks

I want to build a table based on data in a recordset with a hyperlink that calls a method which takes the message id from the link and redirects to another page to view the message. I've tried HTMLAnchors, LinkButtons but none seem to work.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim iUserID As Integer
Dim sMsgId, sMsgSubject, sMsgDateSent, sMsgRead, sMsgFrom, sFirstname As String
iUserID = Session("UserID")
Dim cn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString)
Dim cmd As New SqlCommand()
Dim tblRow As TableRow
Dim tblCell1 As TableCell
Dim tblCell2 As TableCell
Dim tblCell3 As TableCell
Dim tblCell4 As TableCell
tblRow = New TableRow
tblCell1 = New TableCell
tblCell1.Text = ""
tblRow.Cells.Add(tblCell1)
tblCell2 = New TableCell
tblCell2.Text = "From"
tblRow.Cells.Add(tblCell2)
tblCell3 = New TableCell
tblCell3.Text = "Subject"
tblRow.Cells.Add(tblCell3)
tblCell4 = New TableCell
tblCell4.Text = "Received"
tblRow.Cells.Add(tblCell4)
tblMessages.Rows.Add(tblRow)
tblCell1 = Nothing
tblCell2 = Nothing
tblCell3 = Nothing
tblRow = Nothing
cmd.CommandText = "SELECT msg.msg_id, msg.msg_usr_from, usr.usr_firstname, msg.msg_subject, msg.msg_date_sent, msg.msg_read FROM messages msg inner join users usr on msg.msg_usr_to = usr.usr_id WHERE msg.msg_usr_to='" & iUserID & "'"
cmd.Connection = cn
cn.Open()
Dim r As SqlDataReader = cmd.ExecuteReader
Dim objControl As Button
While r.Read()
tblCell1 = New TableCell
tblCell2 = New TableCell
tblCell3 = New TableCell
tblCell4 = New TableCell
tblRow = New TableRow
sMsgId = CStr(r("msg_id"))
sMsgFrom = CStr(r("msg_usr_from"))
sFirstname = CStr(r("usr_firstname"))
sMsgSubject = CStr(r("msg_subject"))
sMsgDateSent = CStr(r("msg_date_sent"))
sMsgRead = CStr(r("msg_read"))
If sMsgRead = "N" Then
tblCell1.Text = "<img width=30px src=images/new_email.png>"
Else
tblCell1.Text = "<img width=30px src=images/email_open.png>"
End If
Dim objLinkbutton As
tblRow.Cells.Add(tblCell1)
tblCell2.Text = sFirstname
tblRow.Cells.Add(tblCell2)
tblCell3.controls.add( HYPERLINK HERE!!!
tblRow.Cells.Add(tblCell3)
tblCell4.Text = FormatDateTime(sMsgDateSent, DateFormat.LongDate)
tblRow.Cells.Add(tblCell4)
If sMsgRead = "N" Then
tblCell2.Font.Bold = True
tblCell3.Font.Bold = True
tblCell4.Font.Bold = True
End If
tblMessages.Rows.Add(tblRow)
tblCell1 = Nothing
tblCell2 = Nothing
tblCell3 = Nothing
tblCell4 = Nothing
tblRow = Nothing
End While
r.Close()
cn.Close()
cn = Nothing
r = Nothing
cmd = Nothing
End Sub
Protected Sub viewmessage(messageid As String)
Context.Items("messageid") = "messageid"
Server.Transfer("viewmessage.aspx")
End Sub
End Class
You have two choices, as I see it.
Massage the data set so it contains the complete URI, with the ID, and then bind to a grid
Use a routine to create the URI and then bind the grid via row binding
Continuing hand binding the table, using hyperlink controls
All are easy enough to do, but the #3 option is the least "ASP.NET" like. I am not fond of hand building tables, when I can do the same with a control, simply by either a) altering the data before bind or b) stopping on the row binding event and adding information.
Use query string to store the id value of the selected link and redirect to the page you want.
try something like this:
Dim a As New HyperLink()
a.Text = "your text"
a.NavigateUrl = "yourPage.aspx?idMsg=" + r["msg_id"]
tblCell3.controls.add(a)

Resources