asp.net looping through dynamic control in a table - asp.net

i have a table which contains questions and a bunch of dynamically created radio button lists, i m trying to write code which will loop through each one of the radio button list and get the value of the selected question value and corresponding question id . i have the following code which returns the selected radio button list value.how i will get questions ids as well as their selected value?
For Each ctrl As Control In form1.Controls
If TypeOf ctrl Is RadioButtonList Then
Dim rbl As RadioButtonList = DirectCast(ctrl, RadioButtonList)
For i As Integer = 0 To rbl.Items.Count - 1
If rbl.Items(i).Selected Then
Dim value As String = rbl.SelectedValue
End If
Next
End If
Next

When creating the radio buttons you should put them into a dictionary (make sure to do so in the Init phase). The String key is assumed to hold the question id:
Dim radios As New Dictionary(Of String, RadioButtonList)
Dim table As DataTable
Sub Page_Init(sender As Object, e As EventArgs)
table = ...
For Each row As DataRow In table.Rows
Dim rbl As New RadioButtonList
' add radio buttons to rbl
radios.Add(row("id").ToString, rbl)
Next
End Sub
Then in the event handler for retrieving the answers you can easily access them:
Sub MyHandler(sender As Object, e As EventArgs)
For Each row As DataRow In table.Rows
Dim value As String = GetAnswer(row("id").ToString)
' do something with the answer ...
Next
End Sub
Function GetAnswer(id As String) As String
For Each item In radios(id)
If item.Selected Then Return item.SelectedValue
Next
Return Nothing
End Function

Related

Add conditional dropdownlist items in ASPX Application (VB)

I have a GridView with a asp:dropdownlist
I am able to add dropdown values using rowdatabound.
However what I need to do, is add specific dropdown list values base on the contents of another cell in that row.
So for example if Row(1) and Cell(2) = MAR001, I want the Dropdown values Four, Five and Six
However if Row(1) and Cell(2) <> MAR001, I want the dropdown values One, Two and Three.
Here is my attempt using a loop, however it doesn't target the dropdown values correctly.
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
For i As Integer = 0 To GridView1.Rows.Count - 1
Dim Name As String = GridView1.Rows(i).Cells(2).Text
If Name = "MAR001" Then
Dim ddl As DropDownList = e.Row.FindControl("ddlQuantity")
Dim numbers As New List(Of String)()
numbers.Add("Four")
numbers.Add("Five ")
numbers.Add("Six")
ddl.DataSource = numbers
ddl.DataBind()
Else
Dim ddl As DropDownList = e.Row.FindControl("ddlQuantity")
Dim numbers As New List(Of String)()
numbers.Add("One")
numbers.Add("Two")
numbers.Add("Three")
ddl.DataSource = numbers
ddl.DataBind()
End If
Next
Else
End If
End Sub
Any help much appreciated.
Not sure if this is what you need, but try finding the textbox first and get the text value of that.
Edit: i just realized you're looping the rows. you don't have to do that - this is the RowDataBound event, so this code happens for every row.
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ddl As DropDownList = e.Row.FindControl("ddlQuantity")
Dim numbers As New List(Of String)()
Dim customerid As String = (e.Row.Cells(2).Text)
If customerid = "MAR001" Then
numbers.Add("Four")
numbers.Add("Five ")
numbers.Add("Six")
Else
numbers.Add("One")
numbers.Add("Two")
numbers.Add("Three")
End If
ddl.DataSource = numbers
ddl.DataBind()
End If

asp.net vb.net gridview, get row id when pressing template field button

I have a template field with a button. I want to press the button and get the row Id so I can return the users selection. I have a regular select button which works fine but the user want the people who are not employee’s to hide the select button. I have this working but since it’s a template field it fires the RoW_command procedure and I cannot seem to get the row index since it is a template field and not the regular Select button. Or I cannot seem to name the Regular select button since it Command field does not have a Name or ID property?
Like I said this works hiding the template field called btnSelect
Private Sub GridView3_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView3.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If (DataBinder.Eval(e.Row.DataItem, "LegacyPersonType") <> "Employee") Then
e.Row.ForeColor = Drawing.Color.Black
e.Row.BackColor = Drawing.Color.Yellow ' This will make row back color yellow
e.Row.FindControl("btnSelect").Visible = False
Else
e.Row.ForeColor = Drawing.Color.Black
e.Row.BackColor = Drawing.Color.White ' the normal employees make white
End If
End If
End Sub
I need to find the Row index when I press btnSelect
Private Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
Dim index As Integer = Convert.ToInt32(e.CommandArgument) ‘ Error invalid
‘ in other words when pressing the tem-plate field there is no e.CommandArgument
‘But clicking the regular select there is
Dim row As GridViewRow = GridView3.Rows(index)
Session("EnterpriseID") = HttpUtility.HtmlDecode(GridView3.Rows(index).Cells(2).Text)
Dim EmployeeType As String = HttpUtility.HtmlDecode(GridView3.Rows(index).Cells(7).Text)
Dim CommonName As String = HttpUtility.HtmlDecode(GridView3.Rows(index).Cells(1).Text)
Dim EnterpriseID = HttpUtility.HtmlDecode(GridView3.Rows(index).Cells(6).Text)
The GridViewRow object knows its row index via the RowIndex property in the RowCommand event, like this:
Private Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
' Get the row by finding the grandparent of the control (button)
' that initiated the command
Dim theGridViewRow As GridViewRow
theGridViewRow = CType(CType(e.CommandSource, Button).Parent.Parent, GridViewRow)
' Get the index value from the grid view row
Dim index As Integer = theGridViewRow.RowIndex
End Sub
Ok I figured it out myself, I made the default Select button on the grid a Template field. since it was the default button it had the necessary code to make it fire. This was the problem with making a template field from scratch. And by making it a template field it then also gave it a name. So in the RowDataBound code the FindControl method above hides it when a person is not an employee. – R2 Builder 1 min ago edit

Maintaining Checkbox State in a Listview Control Pagination ASP.NET

I Have a web form in a asp.net web form 3.5. The listview has a checkbox on the item template, I am trying to retain the state of the checkboxes through pagination . Once I can page through records and preserver this state I need to send this to a print page which takes those ids...I have this working, but it will print only the records on each pagination. Please see live website:
http://rgvpreferred.com/ProviderSearch.aspx
Can you please check my code and suggest how can this be done, the code below is not working.
Protected Sub ListView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ListView1.ItemCommand
Dim myButtonPrint1 As Button = CType(ListView1.FindControl("printButton1"), Button)
If e.CommandSource Is myButtonPrint1 Then
Dim recordsId As New List(Of String)
For Each lvi1 As ListViewItem In ListView1.Items
Dim chb1 As CheckBox = IIf(lvi1.FindControl("CheckBoxPrintProvider1") Is Nothing, IIf(lvi1.FindControl("CheckBoxPrintProvider3") Is Nothing, lvi1.FindControl("CheckBoxPrintProvider4"), lvi1.FindControl("CheckBoxPrintProvider3")), lvi1.FindControl("CheckBoxPrintProvider1"))
If chb1.Checked = True Then
Dim param1 As String
param1 = DirectCast(lvi1.FindControl("lblId1"), Label).Text
recordsId.Add(param1)
End If
Next
' Store in session to be pulled out in the Printable Page
Session("Records") = recordsId
Response.Redirect("PrintableProviderList.aspx")
End If
End Sub
'Trying to Preserve states
Private ReadOnly Property IDs() As List(Of Integer)
' Create a list of ID's that are selected. ID's is the primary
' Key for this table
Get
If Me.ViewState("IDs") Is Nothing Then
Me.ViewState("IDs") = New List(Of Integer)()
End If
Return CType(Me.ViewState("IDs"), List(Of Integer))
End Get
End Property
Protected Sub AddRowstoIDList()
' Loop through all the current items in the Listview
For Each lvi As ListViewDataItem In ListView1.Items
' Find the checkbox in each row
Dim chkSelect As CheckBox = CType(lvi.FindControl("CheckBoxPrintProvider1"), CheckBox)
' If the checkbox is ticked then add the corresponding ID to our private
' list
If (Not (chkSelect) Is Nothing) Then
' Get the ID from the datakeynames property
Dim ID As Integer = Convert.ToInt32(ListView1.DataKeys(lvi.DisplayIndex).Value)
If (chkSelect.Checked AndAlso Not Me.IDs.Contains(ID)) Then
' Add the ID to our list
Me.IDs.Add(ID)
ElseIf (Not chkSelect.Checked AndAlso Me.IDs.Contains(ID)) Then
' Not checked - remove the ID from our list
Me.IDs.Remove(ID)
End If
End If
Next
End Sub
Protected Sub ListView1_PagePropertiesChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.PagePropertiesChangingEventArgs) Handles ListView1.PagePropertiesChanging
AddRowstoIDList()
End Sub
Protected Sub ListView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewSortEventArgs) Handles ListView1.Sorting
AddRowstoIDList()
End Sub
Protected Sub ListView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ListView1.ItemDataBound
' Get each Listview Item on DataBound
Dim lvi As ListViewDataItem = e.Item
If (lvi.ItemType = ListViewItemType.DataItem) Then
' Find the checkbox in the current row
Dim chkSelect As CheckBox = CType(lvi.FindControl("CheckBoxPrintProvider1"), CheckBox)
' Make sure we're referencing the correct control
If (Not (chkSelect) Is Nothing) Then
' If the ID exists in our list then check the checkbox
Dim ID As Integer = Convert.ToInt32(ListView1.DataKeys(lvi.DisplayIndex).Value)
chkSelect.Checked = Me.IDs.Contains(ID)
End If
End If
End Sub
you have to save the selected checkboxes before pagination .
see this link. it should help you:
http://evonet.com.au/maintaining-checkbox-state-in-a-listview/

get value of label when button clicked in nested repeater asp.net vb

I have nested repeaters, each item in the nested repeater has a label and a button on it, i want to beable to access the label.text when the button is clicked, I think i'm nearly there as I can return the index of the repeater and nested repeater that is clicked, i'm just having some trouble finding the label itself.
You might be able to help me without me posting the repeater code. Here is my code behind for when the button is clicked.
Protected Sub btnEditUser_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim btnEditUser As Button = DirectCast(sender, Button)
Dim reClient As RepeaterItem = DirectCast(btnEditUser.NamingContainer.Parent.Parent, RepeaterItem)
Dim reUser As RepeaterItem = DirectCast(btnEditUser.NamingContainer, RepeaterItem)
Dim selectedClient As Integer = reClient.ItemIndex
Dim selectedUser As Integer = reUser.ItemIndex
Dim UserId As Label = DirectCast(reClients.Items(selectedClient).FindControl("lUserName"), Label)
Response.Write(selectedClient & " " & selectedUser & " " & UserId.Text)
End Sub
I'm currently getting this error 'Object reference not set to an instance of an object.' when trying to write the value of UserId.Text so i think i've got it slightly wrong in this line:
Dim UserId As Label = DirectCast(reClients.Items(selectedClient).FindControl("lUserName"), Label)
This is just a guess, but sometimes you get errors like this when not all rows contain the control you're looking for. Often the code loops through the rows in order, hits a header row first that doesn't contain the relevant control, and fails.
Here is a good MSDN article - Locating a Control Inside a Hierarchy of Naming containers.
Private Function FindControlRecursive(
ByVal rootControl As Control, ByVal controlID As String) As Control
If rootControl.ID = controlID Then
Return rootControl
End If
For Each controlToSearch As Control In rootControl.Controls
Dim controlToReturn As Control =
FindControlRecursive(controlToSearch, controlID)
If controlToReturn IsNot Nothing Then
Return controlToReturn
End If
Next
Return Nothing
End Function
Try it,
Dim UserId As Label =DirectCast(FindControlRecursive(repClient,"lUserName"),Label)

How to retrieve the selected row value using command row in gridview?

i have a button in gridview whose command name is "hold" i want when i click n hold button of first row then the whole row values will be transfererd to default2.aspx ...
and if i click the hold button of gridview second row then the second row value will be transferred to Default2.aspx ,,how to do that ?
i m using that ...but it always transfer the 1st row value even i select first last or middle row ..in gridview ....
whats wrong in this code ?
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
For Each myRow As GridViewRow In GridView1.Rows
'Find the checkbox
Dim lab5 As Label = DirectCast(myRow.FindControl("Label5"), Label)
If e.CommandName = "feedback" Then
Me.Response.Redirect("~/view_feedback.aspx?" & "serv_code=" & lab5.Text.ToString)
End If
Next
End Sub
...assuming your posting back the whole page and not using ajax the GridView1_RowCommand will be fired whenever your hold button is clicked, immediately.
As your code is written now you're trying to loop through all rows, and parsing them in turn. However, you are redirecting to your view_feedback.aspx page on the first row if your commandname is Feedback. The first row will be the only one ever processed because your redirect moves the current web request's execution to the new page.
Pass the row index to your command in the CommandArgument property as specified in this example and use it rather than looping through all rows (if you're only processing a single row upon button click anyway).
try this code
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "feedback" Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim myRow As GridViewRow = GridView1.Rows(index)
Dim lab5 As Label = DirectCast(myRow.FindControl("Label5"), Label)
Me.Response.Redirect("~/view_feedback.aspx?" & "serv_code=" & lab5.Text.ToString)
End If
End Sub

Resources