Radiobuttonlist results not working when rbl's dynamically created - asp.net

I have 20 radiobuttonlists which are dynamically created - then declared when a form is submitted.
I also have some code which totals the number of answered questions and the total value of the answered questions. - this code used to work when the radiobuttonlists were hard coded into the page, but it now does not. - I am writing the number of questions answered and the total value of all answers to the page but they come back as 0.
Can anyone see why this might not work now that the radiobuttonlists are dynamically created.?
Code behind:
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
For i As Integer = 1 To 20
Dim TableRow As New TableRow()
Dim TableRowCell_1 As New TableCell()
TableRow.Cells.Add(TableRowCell_1)
holidayQuestionnaireTable.Rows.Add(TableRow)
Dim question As New RadioButtonList
question.ID = "question" & i
question.Items.Insert(0, new listitem("", "1"))
question.Items.Insert(1, new listitem("", "2"))
TableRowCell_1.Controls.Add(question)
Next
End Sub
...
Sub btnSendFeedback_Click(sender as Object, e as EventArgs)
Dim question1 As RadioButtonList = DirectCast(Page.FindControl("question1"), RadioButtonList)
Dim question2 As RadioButtonList = DirectCast(Page.FindControl("question2"), RadioButtonList)
Dim question3 ...
...
Dim question19 As RadioButtonList = DirectCast(Page.FindControl("question19"), RadioButtonList)
Dim question20 As RadioButtonList = DirectCast(Page.FindControl("question20"), RadioButtonList)
Dim rblCount As Double
Dim total As Double
Dim avg As Double
For Each ctrl As UI.Control In Me.myPanel.Controls
If TypeOf ctrl Is RadioButtonList Then
Dim rbl As RadioButtonList = DirectCast(ctrl, RadioButtonList)
If rbl.SelectedIndex > -1 And not rbl.ID = "question18" Then
Dim value As Double = Double.Parse(rbl.SelectedValue)
total += value
rblCount += 1
End If
End If
Next
Response.Write(rblCount & " - " & total & " - " & (total / rblCount))
End Sub
Body:
<asp:Placeholder ID="myPanel" runat="server">
<asp:Table runat="server" CellPadding="0" CellSpacing="0" GridLines="None" HorizontalAlign="Center" CssClass="ratingtable" ID="holidayQuestionnaireTable" />
<asp:Button OnClick="btnSendFeedback_Click" runat="server" Text="Submit..." ID="submitbutton" />
</asp:Placeholder>

You have changed the content of your panel and added a Table instead of using the Panel to add the RadioButtonLists directly. FindControl will only look into the NamingContainer of the Panel and not of its child controls' NamingContainer. Searching through the control-collection of the Panel does also not work because the RBL's are inside of the Table that is inside of the Panel. Therefore you have to loop the TableRows to get the RBL's. Have a look:
For Each row As TableRow In Me.holidayQuestionnaireTable.Rows
For Each cell As TableCell In row.Cells
For Each ctrl As Control In cell.Controls
If TypeOf ctrl Is RadioButtonList Then
Dim rbl As RadioButtonList = DirectCast(ctrl, RadioButtonList)
If rbl.SelectedIndex <> -1 AndAlso rbl.ID <> "question18" Then
Dim value As Int32 = Int32.Parse(rbl.SelectedValue)
total += value
rblCount += 1 'count only the selected RadiobuttonLists'
End If
End If
Next
Next
Next
If you want to use the FindControl-approach, you have to use the NamingContainer of each radioButtonList and that is the TableRow. So this would also work, but is very static and error-prone:
Dim question1 As RadioButtonList = DirectCast(Me.holidayQuestionnaireTable.Rows(0).FindControl("question1"), RadioButtonList)
Dim question2 As RadioButtonList = DirectCast(Me.holidayQuestionnaireTable.Rows(1).FindControl("question2"), RadioButtonList)
Dim question3 As RadioButtonList = DirectCast(Me.holidayQuestionnaireTable.Rows(2).FindControl("question3"), RadioButtonList)

Related

SelectedValue from dynamically created radiobuttonlist vb

I'm trying to create a quiz webpage in Visual Studio 2012 and have a little trouble getting the selected value from a dynamically created radiobuttonlist inside a table.
This is how I create the radiobuttonlist (and add it to the table)
Dim NewRow As New TableRow
Dim NewCell As New TableCell
Dim rblOptions As New RadioButtonList
rblOptions.ID = "Option" & intQuestion.ToString
NewCell.Controls.Add(rblOptions)
NewRow.Cells.Add(NewCell)
'Questions is a table
Questions.Rows.Add(NewRow)
This is how I am trying to get the selectedvalue from the radiobuttonlist after the users hits a button.
Dim rbl As RadioButtonList = DirectCast(Page.FindControl("Option" & intQuestion.ToString), RadioButtonList)
If rbl.SelectedValue.ToString = sdrGetQuestions.Item(0).ToString Then
intScore += 1
End If
In both cases the variable intQuestion = 0.
When running the program I come across the error:
Object reference not set to an instance of an object.
On this line:
If rbl.SelectedValue.ToString = sdrGetQuestions.Item(0).ToString Then
Which I think obviously means the program couldn't find the control it had to place in rbl. I'm couldn't find any answers online...
Could anyone point me in the right direction?
This is my .aspx code.
<asp:Table ID="Questions" runat="server">
</asp:Table>
<asp:Button ID="SaveButton" runat="server" Text="Save" />
This is my code behind file code.
I have added dynamic drop-down list.
On save button click, I am retrieving selected value.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim NewRow As New TableRow
Dim NewCell As New TableCell
Dim rblOptions As New RadioButtonList
rblOptions.ID = "Option1"
rblOptions.Items.Add(New System.Web.UI.WebControls.ListItem("1", "1"))
rblOptions.Items.Add(New System.Web.UI.WebControls.ListItem("2", "2"))
rblOptions.Items.Add(New System.Web.UI.WebControls.ListItem("3", "3"))
NewCell.Controls.Add(rblOptions)
NewRow.Cells.Add(NewCell)
'Questions is a table
Questions.Rows.Add(NewRow)
End Sub
Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
If Page.IsValid Then
Dim rbl As RadioButtonList = DirectCast(Questions.FindControl("Option1"), RadioButtonList)
If rbl.SelectedValue.ToString = "ExpectedValue" Then
End If
End If
End Sub

Delete and Maintain Items on GridView

Sorry for the previous question I've posted. So here's my problem again, here's my code for the gridview.
`
If e.CommandName = "DeleteItem" Then
Dim gvItems As GridView = CType(sender, GridView)
Dim gvparent As GridViewRow = CType(gvItems.NamingContainer, GridViewRow)
'(gvparent.Cells(2).Text)
If gvItems.Rows.Count = 1 Then
lblPopup.Text = "There must be atleast one row."
mpeError.Show()
Exit Sub
End If
Program.oEquipmentLoan.sTransactionCode = gvparent.Cells(3).Text
'Dim gvItem As GridView = TryCast(gvitems.FindControl("gvItems"), GridView)
'For Each gvRow As GridViewRow In gvitems.Rows
' Dim chkItem As CheckBox = DirectCast(gvRow.FindControl("chkSelectItems"), CheckBox)
' If (chkItem.Checked) Then
' Program.oEquipmentLoan.iItemNumber = gvRow.Cells(2).Text
' oSQLEquipmentLoan.DeleteEquipmentLoanItem(Program.oEquipmentLoan)
' End If
'Next
'loadGVGetTransactionLog()
Dim icount As Integer = 0
For Each gvRow As GridViewRow In gvItems.Rows
Dim chkItem As CheckBox = DirectCast(gvRow.FindControl("chkSelectItems"), CheckBox)
If (chkItem.Checked) Then
icount += 1
End If
Next
If icount > 0 Then
For Each gvRow As GridViewRow In gvItems.Rows
Dim chkItem As CheckBox = DirectCast(gvRow.FindControl("chkSelectItems"), CheckBox)
If (chkItem.Checked) Then
Program.oEquipmentLoan.iItemNumber = gvRow.Cells(2).Text
oSQLEquipmentLoan.DeleteEquipmentLoanItem(Program.oEquipmentLoan)
End If
Next
Else
Dim gvr As GridViewRow = DirectCast(DirectCast(e.CommandSource, Control).NamingContainer, GridViewRow)
Dim Index As Integer = gvr.RowIndex
Dim gvRowSelected As GridViewRow = gvItems.Rows(Index)
Program.oEquipmentLoan.iItemNumber = gvRowSelected.Cells(2).Text
oSQLEquipmentLoan.DeleteEquipmentLoanItem(Program.oEquipmentLoan)
End If
End If
sIndex = gvTransactionLogViewer.PageIndex
blnCount = True
loadGVGetTransactionLog()
End Sub`
So, this code particularly deletes a selected row on a gridview. My problem is that whenever I delete an item, after it is deleted, I can't maintain to view the list.
Image given Below :
The photo shows on the before part is that when I'm selecting an item to delete. and on the after, when the item is deleted. And as you can see, what I need to maintain is the list of the updated items after I delete something and after it refreshes. Thanks! :)
on your .aspx page you need to do the partial postback to prevent the whole page postback.
you can achieve this using either asp.net ajax update panel "partial page rendering" or jquery.

How to get the ID of a editing textbox in gridview

I want to get the ID of a textbox like below to add validator, the Client ID contains generated string, UniqueID too, but only the ID contains nothing, why?
Protected Sub GridView1_RowDataBound(ByVal sender As GridView, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
'Manipulate only editing row.
If e.Row.RowType = DataControlRowType.DataRow Then
If sender.EditIndex = e.Row.RowIndex Then
'Search textbox and add validators.
For Each cell As TableCell In e.Row.Cells
If cell.Controls.Count = 1 AndAlso TypeOf (cell.Controls(0)) Is TextBox Then
Dim txt As TextBox = DirectCast(cell.Controls(0), System.Web.UI.WebControls.TextBox)
'txt.ID is nothing...why?
SetValidators(cell.Controls, txt.ID)
End If
Next
End If
End If
End Sub
Well here is a workaround if applies to your application ,
Dim txt As TextBox = DirectCast(cell.Controls(0), System.Web.UI.WebControls.TextBox)
//'txt.ID is nothing...why?
// Here you can assign new ID to your control as per your logic
txt.ID = "newID";
SetValidators(cell.Controls, txt.ID)
You can try following code to assign the validator control to the gridview control.
I am not sure what your doing with SetValidators()function.
Protected Sub GridView1_RowDataBound(ByVal sender As GridView, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
'Manipulate only editing row.
If e.Row.RowType = DataControlRowType.DataRow Then
If sender.EditIndex = e.Row.RowIndex Then
'Search textbox and add validators.
For Each cell As TableCell In e.Row.Cells
If cell.Controls.Count = 1 AndAlso TypeOf (cell.Controls(0)) Is TextBox Then
Dim txt As TextBox = DirectCast(cell.Controls(0), System.Web.UI.WebControls.TextBox)
'txt.ID is nothing...why?
SetValidators(cell.Controls, txt.ClientID)
End If
Next
End If
End If
End Sub
Finally, I'v solved that problem by to apply the workaround below.
Dim txt As TextBox = DirectCast(cell.Controls(0), System.Web.UI.WebControls.TextBox)
'The ID is generated by to refer ClientID.
Dim foo = txt.ClientID
'Therefore, already txt.ID is not nothing.
SetValidators(cell.Controls, txt.ID)
Thank you for your cooperation.

Insert value of dynamically created radiobuttonlist in database through programming

I am trying to bind radiobutton list dynamically in programm. But I do
not know how to insert value.
Aspx Page code
<asp:Table ID="tblSponser" runat="server" cellpadding="0" cellspacing="10" Visible="false"></asp:Table>
on dropdownlist selectedindex event I am Binding Radio Button in Code
behind
Protected Sub ddlVotes_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ddlVotes.SelectedIndexChanged
For SponserId = 0 To sponserDtst.Tables(0).Rows.Count - 1
Dim tr As New TableRow
Dim c1 As New TableCell
Dim c2 As New TableCell
Dim rbtyes As New RadioButtonList
rbtyes.ID = "rbtypes" & SponserId
rbtyes.ClientIDMode = UI.ClientIDMode.Static
rbtyes.Items.Add(New ListItem("Yes"))
rbtyes.Items.Add(New ListItem("No"))
rbtyes.RepeatDirection = RepeatDirection.Horizontal
c2.Controls.Add(rbtyes)
c2.Controls.Add(rbtyes)
tr.Controls.Add(c1)
tr.Controls.Add(c2)
tblSponser.Controls.Add(tr)
Below code is not working. How to get value of radiobuttonlist and
store in database on button click event.
Protected Sub btnSubmitVote_Click(sender As Object, e As System.EventArgs) Handles btnSubmitVote.Click
Dim i As Integer
Dim x As Integer = 5
For i = 0 To x - 1
Dim str As String = "rbtypes" & i
Dim rb As RadioButtonList = CType(tblSponser.FindControl(str), RadioButtonList)
Dim ix As String = rb.SelectedValue
Next
At which point in the page load process do you execute your code? You should be doing this in OnInit method in order to work properly.
Take a look at this – it provides a good info on asp.net page life cycle
ASP.NET Page Life Cycle Overview

ASP.NET - Keep DropDownList selection on repeater DataBound

I have two DropDownLists per item on a Repeater.
I am binding both lists to two different lists on the repeater DataBound.
Both lists have an OnSelectedIndexChanged event handler which does some calculations based on the selections in both DropDownLists. Both lists also have AutoPostBack="True".
I need the calculation to be updated immediately. So I added another data binding for the repeater - on the lists' event handler.
This is the problem however - the repeater "resets" the selections to -1 and eventually the first items in both DropDownLists are displayed.
How can I make sure the selections remain after the data binding?
Here is the repeater structure:
<asp:Repeater runat="server" ID="rptCart">
<ItemTemplate>
<tr>
<td class="size"><div><asp:DropDownList runat="server" ID="_selectSize" AutoPostBack="true" OnSelectedIndexChanged="selectChange" EnableViewState="true" TabIndex="<%#Container.ItemIndex%>"></asp:DropDownList></div></td>
<td class="material"><div><asp:DropDownList runat="server" ID="_selectMaterial" AutoPostBack="true" OnSelectedIndexChanged="selectChange" EnableViewState="true" TabIndex="<%#Container.ItemIndex%>"></asp:DropDownList></div></td>
</tr>
</ItemTemplate>
</asp:Repeater>
And the repeater DataBound:
Protected Sub rptCart_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptCart.ItemDataBound
If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType = ListItemType.Item Then
Dim sizeSelect As DropDownList = CType(e.Item.FindControl("_selectSize"), DropDownList)
Dim materialSelect As DropDownList = CType(e.Item.FindControl("_selectMaterial"), DropDownList)
sizeSelect.DataSource = sizeList
sizeSelect.DataBind()
materialSelect.DataSource = materialList
materialSelect.DataBind()
End If
End Sub
And finally the DropDownLists event handler:
Protected Sub selectChange(ByVal sender As DropDownList, ByVal e As System.EventArgs)
Dim listing As New PriceListing
Dim ddl As DropDownList
Dim selectedIndex As Integer
If sender.ID = "_selectSize" Then
For Each rptrItem As RepeaterItem In rptCart.Items
ddl = CType(rptrItem.FindControl("_selectMaterial"), DropDownList)
If ddl.TabIndex = sender.TabIndex Then Exit For
Next
For Each listing In artDecoPricing
If listing.Size = sender.SelectedValue Then Exit For
Next
selectedIndex = ddl.SelectedIndex
ElseIf sender.ID = "_selectMaterial" Then
For Each rptrItem As RepeaterItem In rptCart.Items
ddl = CType(rptrItem.FindControl("_selectSize"), DropDownList)
If ddl.TabIndex = sender.TabIndex Then Exit For
Next
For Each listing In artDecoPricing
If listing.Size = ddl.SelectedValue Then Exit For
Next
selectedIndex = sender.SelectedIndex
End If
Select Case selectedIndex
Case 0
Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Canvas
Case 1
Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Acrylic
Case 2
Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Framed
Case 3
Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Framed
End Select
Cart.SaveOrder()
rptCart.DataSource = Cart.Order.Items
rptCart.DataBind()
End Sub
Thank you very much in advance!
You could store the old selection:
Dim sizeSelect As DropDownList = CType(e.Item.FindControl("_selectSize"), DropDownList)
Dim materialSelect As DropDownList = CType(e.Item.FindControl("_selectMaterial"), DropDownList)
Dim sizeSelectedIndex = sizeSelect.SelectedIndex
Dim materialSelectedIndex = materialSelect.SelectedIndex
' do the databinding ... '
sizeSelect.SelectedIndex = If(sizeSelectedIndex < sizeSelect.Items.Count -1, sizeSelectedIndex, -1)
materialSelect.SelectedIndex = If(materialSelectedIndex < materialSelect.Items.Count -1, materialSelectedIndex, -1)

Resources