I have a DetailsView which contains several text boxes and also a DropDownList.
Now, what I want to do is to write an SelectedIndexChanged event for that DropDownList, but my problem is that I cannot reach it anymore/reference it.
If I just put a DropDownList right on the form it´s no problem but now winds it is inside the DetailsView it seems impossible to reach it.
Any suggestions?
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Protected Sub DetailsViewAvtaleInfo_PageIndexChanging1(sender As Object, e As DetailsViewPageEventArgs) Handles DetailsViewAvtaleInfo.PageIndexChanging
Dim DropDownListContractType As DropDownList = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("DropDownListContractType"), DropDownList)
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.Text = "Kjøp" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
I know this is not right, but its as far as I get. I would want to just Write the code within the following sub but it just will not work:
Protected Sub DropDownListContractType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListContractType.SelectedIndexChanged
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.Text = "Leasing" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
You did not post the markup for the dropdownlist, it should be like below (Attached the method to the event):
<asp:DropDownList ID="DropDownListContractType" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownListContractType_SelectedIndexChanged">
<asp:ListItem Text="Kjøp" Value="2"></asp:ListItem>
<asp:ListItem Text="Leasing" Value="1"></asp:ListItem>
</asp:DropDownList>
Your code also have some issues:
Should be DropDownList.SelectedItem.Text instead of
DropDownList.Text.
You have to cast the sender to DropDownList in DropDownListContractType_SelectedIndexChanged method.
You have to find the NamingContainer of DropDownList in DropDownListContractType_SelectedIndexChanged method
If you have the following code, it should work:
Protected Sub DropDownListContractType_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim DropDownListContractType As DropDownList = DirectCast(sender, DropDownList)
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(DropDownListContractType.NamingContainer.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.SelectedItem.Text = "Leasing" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
Protected Sub DetailsViewAvtaleInfo_PageIndexChanging(sender As Object, e As DetailsViewPageEventArgs) Handles DetailsViewAvtaleInfo.PageIndexChanging
Dim DropDownListContractType As DropDownList = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("DropDownListContractType"), DropDownList)
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.SelectedItem.Text = "Kjøp" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
I have tested the code above. If you have any issue, try to copy/paste the markup and code.
You can download my test project to compare with yours here.
Related
I have the following code in the page source:
<asp:Button ID="Button1" runat="server" Text="Button" />
And in code behind page:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 9
Dim box As New TextBox()
box.ID = "textBox" + CStr(i)
box.Width = 20
box.Text = CStr(i)
box.TabIndex = CShort(i + 1)
AddHandler box.TextChanged, AddressOf ClickBox
panel1.Controls.Add(box)
Next
End Sub
Private Sub ClickBox(sender As Object, e As EventArgs)
Dim boxUsed = DirectCast(sender, TextBox)
boxUsed.BackColor = Drawing.Color.Crimson
End Sub
The problem is TextChange event for texboxes doesn't fire.
Two things. First:
box.AutoPostBack = True
Second:
Since you're creating textboxes dynamically, they will be gone between every postback, unless you re-create them in the Page_Load event.
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
I have a "cart" Repeater, where every item has a couple of controls in it. The ones we're focusing on are two DropDownLists, a LinkButton and a TextBox. The lists are on one validation group and the button & textbox are on another.
Both lists have an OnSelectedIndexChanged event handler which does some calculations based on the selections in both DropDownLists. Both lists also have AutoPostBack="True".
The button has an OnClick handler which also does some calculations according to the number in the textbox.
I need the calculations to be updated immediately - so I added another data binding for the Repeater - on each event handler
The problem is - I can't get the value from the TextBox after I click on one of the DropDownLists. It always comes off as 1. In the background, the OnSelectedIndexChanged event handler fires first, and the buttons' OnClick will fires after it. That only happens after I change one of the lists - and it happens every time I click that button from that moment on. Before that - everything is normal on all controls.
What do you think? Below is some code (I hope it's not too much, I included everything that's taking part) - Thank you very much!
Here's the repeater template:
<ItemTemplate>
<tr>
<td class="size"><div><asp:DropDownList runat="server" ID="_selectSize" AutoPostBack="true" OnSelectedIndexChanged="selectChange" EnableViewState="true" TabIndex="<%#Container.ItemIndex%>" ValidationGroup="doNotValidate"></asp:DropDownList></div></td>
<td class="material"><div><asp:DropDownList runat="server" ID="_selectMaterial" AutoPostBack="true" OnSelectedIndexChanged="selectChange" EnableViewState="true" TabIndex="<%#Container.ItemIndex%>" ValidationGroup="doNotValidate"></asp:DropDownList></div></td>
<td class="quantity">
<div>
<div class="quantity_container"><asp:TextBox runat="server" ID="_txtAmount" name="quantity_<%#Container.ItemIndex%>" ValidationGroup="vCart"></asp:TextBox></div>
<div><asp:LinkButton runat="server" CssClass="refresh" id="_refreshCart" ValidationGroup="vCart"></asp:LinkButton></div>
</div>
</td>
</tr>
</ItemTemplate>
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 OrderItem As ProxyMarket.Item = CType(e.Item.DataItem, ProxyMarket.Item)
Dim btnRemoveProduct As LinkButton = CType(e.Item.FindControl("_removeProduct"), LinkButton)
Dim btnRefreshCart As LinkButton = CType(e.Item.FindControl("_refreshCart"), LinkButton)
Dim txtAmount As TextBox = CType(e.Item.FindControl("_txtAmount"), TextBox)
Dim sizeSelect As DropDownList = CType(e.Item.FindControl("_selectSize"), DropDownList)
Dim materialSelect As DropDownList = CType(e.Item.FindControl("_selectMaterial"), DropDownList)
btnRemoveProduct.CommandName = OrderItem.ID
btnRefreshCart.CommandName = OrderItem.ID
txtAmount.Text = OrderItem.Units
AddHandler btnRemoveProduct.Click, AddressOf removeProduct
AddHandler btnRefreshCart.Click, AddressOf refreshCart
sizeSelect.DataSource = sizeList
sizeSelect.DataBind()
sizeSelect.SelectedIndex = s
materialSelect.DataSource = materialList
materialSelect.DataBind()
materialSelect.SelectedIndex = m
End If
End Sub
Here is 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
s = sender.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
s = ddl.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.Alucobond
End Select
Cart.SaveOrder()
s = sender.SelectedIndex
m = selectedIndex
rptCart.DataSource = Cart.Order.Items
rptCart.DataBind()
End Sub
And finally, the LinkButton OnClick handler:
Protected Sub refreshCart(ByVal sender As Object, ByVal e As System.EventArgs)
Dim btnRefreshCart As LinkButton = CType(sender, LinkButton)
Dim amountStr As String
Dim amount As Integer
amountStr = CType(btnRefreshCart.Parent.FindControl("_txtAmount"), TextBox).Text
If IsNumeric(amountStr) Then
amount = CDbl(amountStr)
Else
amount = -1
End If
amount = IIf(amount > 0, amount, -30)
For Each Item As ProxyMarket.Item In Cart.Order.Items
If Item.ID = btnRefreshCart.CommandName Then
Item.Units = amount
Cart.Edit_Product(btnRefreshCart.CommandName, amount)
Exit For
End If
Next
rptCart.DataSource = Cart.Order.Items
rptCart.DataBind()
End Sub
Thank you :)
I found a solution!
Apparently this is happening because of a viewstate limitation in ASP.NET which causes the OnSelectedIndexChanged to fire on Page_Load regardless if the user actually selected a different value.
So when the event handler fires, I am checking whether it is the DropDownLists which called me or a different control - that prevents the event from firing when it doesn't need to - and keeps all event handling on the page intact:
Protected Sub selectChange(ByVal sender As DropDownList, ByVal e As System.EventArgs)
Dim senderClientID = Page.Request.Params.Get("__EVENTTARGET")
' Run ONLY if the relevant select control was clicked,
' otherwise this is only fired because of ASP.NET limitations,
' and will screw up the original event:
If senderClientID.IndexOf("_selectSize") <> -1 Or senderClientID.IndexOf("_selectMaterial") <> -1 Then
'do stuff
I know this has already been answered but I was having a very similar problem, with a completely different solution and as this is the first post that appeared in google I thought I would add it here.
I had a link button and when clicking it, but only in IE9, it appeared to activate another button on the page and call it's event rather than it's own.
After much messing about and googling, I realised that it wasn't just my button that was activating the other button it was if I clicked anywhere in a particular section of my page.
I eventually found the problem after completely stripping down my page. It was this:
<label style="width: 100%" />
an empty label tag. Once deleted all was fine.
I'm trying to get a drop down list control to work in FormView. I need to have the list be a filtered view of a certain table and still be bound to a field in the data I'm editing. I've tried setting the item data programatically, ant that works but then the data binding
doesn't work, It tries to insert null into the database.
This is the code I've tried. I've also tried doing the same thing in several other events, it still tries to insert null into the database.
<asp:DropDownList ID="lstManagers" runat="server"
OnDataBound ="ManagersLoad"
SelectedValue='<%# Bind("UserName") %>' Width="100%"
DataSourceID="TimeOff" DataTextField="UserName" DataValueField="UserName">
</asp:DropDownList>
Protected Sub ManagersLoad(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lst As DropDownList = FormView1.FindControl("lstManagers")
'get list of managers
Using ef As New TimeOffData.TimeOffEntities
For Each item As ListItem In lst.Items
Dim li As ListItem = item
item.Text = (From x In ef.TimeOffUsers Where x.UserName = li.Value Select x.FirstName & " " & x.LastName).FirstOrDefault
Next
End Using
End Sub
I took all the data binding stuff of the control and just decide it would be easier to do it manually. I've changed the code to this,
Protected Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInserting
Dim lst As DropDownList = FormView1.FindControl("lstManagers")
e.Values.Item("ManagerName") = lst.SelectedValue
End Sub
Protected Sub ManagersLoad(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lst As DropDownList = FormView1.FindControl("lstManagers")
'get list of managers
Using ef As New TimeOffData.TimeOffEntities
Dim mng = From x In ef.TimeOffUsers Where x.IsManager = True
For Each item In mng
lst.Items.Add(New ListItem(item.FirstName & " " & item.LastName, item.UserName))
Next
End Using
End Sub
I have a ListView that populates and displays a user's data (via a profile system in VWD 2008) during Page_Load and also when I go from the EditItemTemplate to the ItemTemplate.
When I go to the edit screen again, my DropDownList and RadioButtonList controls display the first items in the corresponding tables instead of the correct profile values.
I don't understand why the controls populate correctly the first and second times but not on the third time (that's right, the third time is NOT a charm).
Can someone can help me understand how to solve this problem?
ItemTemplate:
<asp:DropDownList ID="ddlTState" AppendDataBoundItems="True"
DataSourceID="srcState" DataTextField="StateName" DataValueField="StateName"
Enabled="False" TabIndex="125" runat="server" />
EditItemTemplate:
<asp:DropDownList ID="ddlEState" AppendDataBoundItems="true"
DataSourceID="srcState" DataTextField="StateName"
DataValueField="StateName" TabIndex="125" runat="server">
<asp:ListItem Text="--State--" Value="" />
VB code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
lsv = Util.FindChild(Me, "lsvProfile")
'If Not IsPostBack Then
ddl = Util.FindChild(lsv, "ddlEState") 'Util.FindChild = my version of FindControl
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.State
ddl = Util.FindChild(lsv, "ddlTState")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.State
'End If
End Sub
It could be it's hitting the null condition and not writing; a better way to handle items/edit template is to tap into the ItemDataBound event or ItemCreated event handlers. This features at the time it creates the row, and you will have better success there. I believe you could also leverage ItemEditing, which fires when a row switches to edit mode, as another way to process an edit action.
EDIT: Try to do this:
protected void lsvProfile_ItemDataBound(..)
{
if (e.Item.ItemTYpe == ListViewItemType.DataItem)
{
DropDownList d = e.Item.FindControl("ddlTState") as DropDownList;
}
}
And debug to see if that is null or not null. The only time that should be null is if its rendering the header/footer or the edit item... That should work though, I do that all the time.
HTH.
Thanks, Brian. I resolved it with this code before I read your latest post:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
lsv = Util.FindChild(Page, "lsvProfile")
If Not IsPostBack Then
Try
lsv.EditIndex = 0
rbl = Util.FindChild(lsv, "rblEGender")
If rbl IsNot Nothing Then rbl.SelectedValue = Profile.Gender
ddl = Util.FindChild(lsv, "ddlEState")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.State
ddl = Util.FindChild(lsv, "ddlEBirthDay")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.BirthDay
ddl = Util.FindChild(lsv, "ddlEBirthMo")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.BirthMo
Catch ex As Exception
End Try
End If
End Sub
Protected Sub lsvProfile_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lsvProfile.ItemDataBound
ddl = Util.FindChild(Me, "ddlEState")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.State
ddl = Util.FindChild(Me, "ddlEBirthMo")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.BirthMo
ddl = Util.FindChild(Me, "ddlEBirthDay")
If ddl IsNot Nothing Then ddl.SelectedValue = Profile.BirthDay
rbl = Util.FindChild(Me, "rblEGender")
If rbl IsNot Nothing Then rbl.SelectedValue = Profile.Gender
End Sub