get values of dynamic checkboxes - asp.net

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

Related

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

How to build the gridview from 2 tables and save co-ordinates mapping in 3'rd table in asp.net web form?

I am having Component table, Role table, and ComponentRoleMapping table in database. Please look at the image below. I want to populate the column Component names as first column filled with all rows and roles should be the first row of grid from Role table. All cell have to have check box. The matrix co-ordinate have to save that coordination in ComponentRoleMapping table by clicking on any check box. In short to populate many to many relationship among components and Roles I need this view. I am using asp.net web form and gridview control to populate this. how to populate single gridview from 2 tables / datatables ? Or any other control I can use here. Or any article I can follow for exact purpose?
you need a RoleComponent table which is a simple table of pk's that maps a Component to a Role. Sample table:
CREATE TABLE [dbo].[RoleComponent](
[role_pk] [int] NOT NULL,
[component_pk] [int] NOT NULL
) ON [PRIMARY]
A checkbox is initially checked if an entry in this table exists for a specific role and component.
When a user:
Checks a checkbox: insert a row for the given role_pk and component_pk
UnCheck a checkbox: delete a row for the given role_pk and component_pk
To get the grid of checkboxes as you have in your display you are going to need to return a pivot table of bit fields. Pivot tables are not simple in SqlServer. In fact they are downright annoying.
A Repeater might be a better option.
I am answering my own question, It might helpful to others. Rather to use Grid control I used Html table only.
Here Dt1 has Components, Dt2 has Roles and Dt3 used for to check active status. May be some dead code in this but, running perfect.
Private Sub GenerateTable(dt2 As DataTable, dt1 As DataTable, dt3 As DataTable)
Dim table As New Table()
Dim row As TableRow = Nothing
'Add the Headers
row = New TableRow()
'Empty
Dim headerCellEmpty As New TableHeaderCell()
headerCellEmpty.Text = ""
headerCellEmpty.Attributes("style") = "border:1px solid black;text-align:center;"
row.Cells.Add(headerCellEmpty)
For i As Integer = 0 To dt2.Rows.Count - 1
Dim headerCell As New TableHeaderCell()
headerCell.Text = dt2.Rows(i)(0).ToString()
headerCell.ID = dt2.Rows(i)(1).ToString()
'Check All Components
Dim chkAllComponent As New CheckBox()
chkAllComponent.ID = "allcomponents_" + dt2.Rows(i)(1).ToString()
chkAllComponent.Text = dt2.Rows(i)(0).ToString()
headerCell.Controls.Add(chkAllComponent)
headerCell.Attributes("style") = "border:1px solid black;text-align:center;width:15%;"
row.Cells.Add(headerCell)
Next
table.Rows.Add(row)
'Add the Column values
For i As Integer = 0 To dt1.Rows.Count - 1
row = New TableRow()
For j As Integer = 0 To dt1.Columns.Count - 2
Dim cell As New TableCell()
cell.Text = dt1.Rows(i)(j).ToString()
cell.ID = dt1.Rows(i)(j + 1).ToString()
'Check All Roles
Dim chkAllRoles As New CheckBox()
chkAllRoles.ID = "allroles_" + dt1.Rows(i)(j + 1).ToString()
chkAllRoles.Text = dt1.Rows(i)(j).ToString()
cell.Controls.Add(chkAllRoles)
row.Cells.Add(cell)
Next
' Add the TableRow to the Table
table.Rows.Add(row)
Next
If table.Rows.Count > 0 Then
If table.Rows(0).Cells.Count > 0 Then
'Add check boxes
Dim allColumnsCountinTable As Integer = table.Rows(0).Cells.Count
For Each tr As TableRow In table.Rows
Dim rowIndex As Integer = table.Rows.GetRowIndex(tr)
If rowIndex = 0 Then
Else
For f As Integer = 1 To allColumnsCountinTable - 1
Dim cell As New TableCell()
Dim roleid = table.Rows(rowIndex).Cells(0).ID
Dim roleId1 As Guid = New Guid(roleid)
Dim componentid = table.Rows(0).Cells(f).ID
Dim Check1 As New CheckBox()
Check1.ID = "chk_" + roleid + "_" + componentid
Dim configurations = From p In dt3.AsEnumerable() Select p
If (configurations.Any(Function(coffee) c.Field(Of Integer)("ComponentId") = componentid And c.Field(Of Guid)("RoleId") = roleId1)) Then
Dim isActive = configurations.Where(Function(coffee) c.Field(Of Integer)("ComponentId") = componentid And c.Field(Of Guid)("RoleId") = roleId1).FirstOrDefault()("IsActive")
If isActive = True Then
Check1.Checked = True
Else
Check1.Checked = False
End If
Else
Check1.Checked = False
End If
Check1.Attributes("Name") = "checkbox"
cell.Attributes("style") = "border:1px solid black;text-align:center;"
cell.Controls.Add(Check1)
tr.Cells.AddAt(f, cell)
Next
End If
tr.Attributes("style") = "color:red; border:1px solid black;"
Next
End If
End If
'Styling
Panel1.Controls.Add(table)
End Sub

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?

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