SelectedIndexChange Not Firing - asp.net

I'm having issue with a dropdownlist updating a textbox, both held within a listview, within an update panel which in turn is in an item template.
Updated
I have got this working with the same code without the above containers in a different web page on the same project, however having trouble linking it with the lisview and other containers.
I am unsure of where the problem lies, the onClick isn't firing unless there's a call back to the server, regardless whether the drop down is contained within the containers mentioned above.
Any help would be greatly appreciated, thanks in advance.
Using asp (1st) and VB code behind (2nd).
<InsertItemTemplate>
<asp:panel runat="server" ChildrenAsTriggers="true" UpdateMode="Always">
<asp:ListView ID="ListView1" runat="server" InsertItemPosition="FirstItem" IAllowPaging="True" EnableViewState="true">
<tr>
<td>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Details")%>' TextMode="MultiLine" />
</td>
<td>
<asp:DropDownList ID="DLL" runat="server" OnSelectedIndexChanged="DLL_SelectedIndexChanged" AutoPostBack="true "EnableViewState="true">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="2">No</asp:ListItem>
<asp:ListItem Value="3">Maybe</asp:ListItem>
<asp:ListItem Value="4">I dont know</asp:ListItem>
<asp:ListItem Value="5">Can you repeat</asp:ListItem>
<asp:ListItem Value="6">the question</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</asp:panel>
</InsertItemTemplate>
Code behind
Protected Sub DDL_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddl As DropDownList = DirectCast(sender, DropDownList)
Dim listviewItemThing = DirectCast(sender.parent.NamingContainer, ListViewItem)
Dim tb As TextBox = DirectCast(ddl.NamingContainer.FindControl("TextBox2"), TextBox)
If ddl.SelectedValue = 1 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\1.txt")
ElseIf ddl.SelectedValue = 2 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\2.txt")
ElseIf ddl.SelectedValue = 3 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\3.txt")
ElseIf ddl.SelectedValue = 4 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\4.txt")
ElseIf ddl.SelectedValue = 5 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\5.txt")
ElseIf ddl.SelectedValue = 6 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\6.txt")
Else
tb.Text = ""
End If
End Sub
Update 2
As per request please see attached screen shot of browser console error in debug on VS2013
And expanded error.
Update 3
Added JQuery to try to force PostBack.
function JsFunction() {
__doPostBack('DLL_SelectedIndexChanged', '');
}
ASP link to JQ
<asp:DropDownList ID="DDL" runat="server" Width="120px" OnSelectedIndexChanged="DDL_SelectedIndexChanged" AutoPostBack="true" CausesValidation="false" EnableViewState="true" onchange="javascript:JsFunction()">

You have correct code for your drop down list, so error in other place.
As you see in error message: when you try submit form problem with HtmlEditorExtender.
So just remove or disable it for quick fixing problem.
As for error with HtmlEditorExtender we need a little bit information, of course, if you still need solve it.

Assuming these controls are within the ItemTemplate of your ListView:
FindControl("DDL") won't work, because it's trying to find the control within the page;
ListView1.FindControl("TextBox2") won't work, because there will be multiple instances of TextBox2 within the ListView.
Try this instead:
Dim ddl As DropDownList = DirectCast(sender, DropDownList)
Dim tb As TextBox = DirectCast(ddl.NamingContainer.FindControl("TextBox2"), TextBox)

I assume you haven't got the typo in your actual code:
OnSelectedIndexChanged="DLL_SelectedIndexChanged"
Where the event handler is DDL_SelectedIndexChanged.
Have you put a breakpoint on to check whether the event handler is not being called or if it is bailing out at some point after it fails to do the cast you want it to do?

Related

Dropdown List not setting selectedValue in its databind event

I've currently run into an error with binding causing an error when the value pulled from the database is blank.
In an attempt to fix it I am instead binding the value from the database to a label, and then looping through the items in the combobox's databound event, matching the against the label. If it finds a match, it is supposed to set the selected value of the combobox to the text value of the label (lblSalesManagerValue).
<td align="left">
<asp:Label ID="lblSalesManager" runat="server" Text="Sales Manager:" Width="120px"></asp:Label>
<telerik:RadComboBox ID="cboSalesManager" runat="server" DataSourceID="SalesManagersDataSource" DataTextField="Name" DataValueField="No." Width="149px" OnDataBound="cboSalesManager_DataBound" />
<asp:Label ID="lblSalesManagerValue" runat="server" Text='<%# Bind("SM") %>' Visible="false"></asp:Label>
<asp:Label ID="lblTest" runat="server" Text="" Visible="True"></asp:Label>
<asp:RequiredFieldValidator id="RequiredFieldValidator4" runat="server"
ErrorMessage="Please select Sales Manager." Text=" *" ControlToValidate= "cboSalesManager"></asp:RequiredFieldValidator>
</td>
I am working in VB, using a Telerik RadGrid.
Protected Sub cboSalesManager_DataBound(sender As Object, e As EventArgs)
Dim cbo As RadComboBox = DirectCast(sender, RadComboBox)
Dim gr As GridEditFormItem = DirectCast(cbo.Parent.NamingContainer, GridEditFormItem)
For Each itm As RadComboBoxItem In cbo.Items
If itm.Value.ToString = CType(gr.FindControl("lblSalesManagerValue"), Label).Text Then
cbo.SelectedValue = CType(gr.FindControl("lblSalesManagerValue"), Label).Text
CType(gr.FindControl("lblTest"), Label).Text = CType(gr.FindControl("lblTest"), Label).Text & ";" & cbo.SelectedValue.ToString
End If
Next
End Sub
Everything fires, as I get a semicolon beside my combobox, but the value just won't set for some reason and I am baffled.
Edit: After playing with it some more, I have discovered that nothing from that label will stick. I tried setting the test label (I'd response.write but this is an asynchronous call) and it won't set either.
I figured it out. The combobox was binding before the label. I added a forced
CType(gr.FindControl("lblSalesManagerValue"), Label).DataBind()
And it works perfectly. =)

Using FindControl method of FormView within a Repeater

I need an advice how to correct my code. I am using FindControl method to find TextBox inside Repeater. This is my markup:
<asp:Repeater ID="Repeater1">
HERE ARE SOME OTHER DATA
<ItemTemplate>
<asp:FormView ID="FormViewAddComment" runat="server"
DataSourceID="SqlDataSourceInsertComments" DefaultMode="Insert"
OnItemInserted="FormViewAddComment_ItemInserted"
OnItemInserting="FormViewAddComment_ItemInserting">
<InsertItemTemplate>
<asp:TextBox ID="txtAddComment" runat="server" CssClass="textbox"
Text='<%# Bind("CommentText") %>' Width="200px" />
<asp:Button ID="btnAddComment" runat="server" CssClass="button"
Text="Comment" CommandName="Insert" CausesValidation="false"/>
</InsertItemTemplate>
</asp:FormView>
</ItemTemplate>
</asp:Repeater>
And this is my code behind:
Protected Sub FormViewAddComment_ItemInserting(sender As Object, e As FormViewInsertEventArgs)
Dim FormView As FormView = DirectCast(Repeater1.FindControl("FormViewAddComment"), FormView)
Dim Comment As TextBox = DirectCast(FormView.FindControl("txtAddComment"), TextBox)
If Comment.Text = "" Then
Exit Sub
End If
End Sub
The Comment TextBox is not found and the code throws an Object reference error when it tries to access the Text property.
You can find the textbox inside it using ItemDataBound event.
Thanks
You are accessing "txtAddComment" which is there in FormView,then why are you finding FormView in Repeater and then again in textbox in that...you can directly find out it...
Protected Sub FormViewAddComment_ItemInserting(sender As Object, e As FormViewInsertEventArgs)
If (FormView1.CurrentMode == FormViewMode.Insert)
Dim Comment As TextBox = DirectCast(FormViewAddComment.FindControl("txtAddComment"), TextBox)
If Comment.Text = "" Then
Exit Sub
End If
End Sub
EDIT:-
My point is that you are writting the code in ItemInserting Event of FormView,so there you can directly find the FormView.I would suggest to use NamingContainer property in oredr to find the FormView which has trigged the event,by this way you can find the FormView then you can easily find the TextBox in it.
There is example of NamingContainer for Gridview Here

ASP.net dropdownlist unexpected event firing behavior

I'm experiencing some odd behavior with drop down boxes and I'm hoping someone could explain what's going on. I have a datarepeater that builds out a table of rows. Each row has a dropdownlist (hidden) and a linkbutton (not hidden) in a cell. The expected behavior is that when a user clicks the linkbutton for a specific cell, it fires a server command. This command does a few things but also sets the selected value of the DDL and then sets it visible and sets itself (the linkbutton) hidden. The problem is that the dropdownlist's event should fire every time the selected index changes. But, what ends up happening is that it only fires the first time the user changes the DDL value. After that, the event will stop firing. Also, all of this is in a usercontrol and all the code is inside an updatepanel. As I mention in the code example, if I do not change the ddl value, in the linkbutton event, this behaviors stops but then the DDL wont have the correct value set. Here is my code:
Linkbutton event:
Protected Sub edit_click(ByVal sender As Object, ByVal e As EventArgs)
Dim btn As LinkButton = CType(sender, LinkButton)
Dim userId As String = btn.CommandArgument
Dim ds As New List(Of myObject)
Dim currentChoice As New myObject
Dim parent As RepeaterItem = CType(btn.Parent, RepeaterItem)
Dim lbl As Label = CType(parent.FindControl("userId"), Label)
Dim ma As DropDownList = CType(parent.FindControl("ddlMustApprove"), DropDownList)
Dim maLbl As Label = CType(parent.FindControl("mustApprove"), Label)
'just get a list of values to chose from
ds = Session("userNotificationDS")
currentChoice = ds.Find(Function(p As myObject) p.User.NetworkID = userId)
With maLbl
.Width = 100
.BorderColor = Drawing.Color.DarkBlue
End With
'if I disable this next line, everything works fine (but then the correct selection wont be chosen)
ma.Text = currentChoice.MustApprove
ma.CssClass = ""
maLbl.Visible = False
End Sub
DDL change event:
Protected Sub selection_Change(ByVal sender As Object, ByVal e As EventArgs)
Dim cnt As DropDownList = CType(sender, DropDownList)
Dim parent As RepeaterItem = CType(cnt.Parent, RepeaterItem)
Dim maLbl As Label = CType(parent.FindControl("mustApprove"), Label)
Dim userId As Label = CType(parent.FindControl("userId"), Label)
Dim ds As New List(Of myObject)
'just gets the value to set the DDL to
ds = Session("userNotificationDS")
For Each i As myObjectIn ds
If (i.User.NetworkID = userId.Text) Then
i.MustApprove = cnt.SelectedValue
End If
Next
maLbl.Visible = True
cnt.CssClass = "hidden"
Session("userNotificationDS") = ds
bindData(ds)
End Sub
Here is the Datarepeater in the front end code:
<asp:Repeater ID="dataRepeateUsers" runat="server" EnableViewState="false" OnItemCreated="RepeaterItemCreated" >
<HeaderTemplate>
.... column headers
</HeaderTemplate>
<ItemTemplate>
<tr class="listcolor">
<td style="border:0px; border-right:1px solid #808080 ; border-bottom:0px solid #808080;">
<asp:DropDownList runat="server" ID="ddlMustApprove" CssClass="hidden" OnTextChanged="selection_Change" EnableViewState="true" AutoPostBack="true" >
<asp:ListItem Text="True" Value="True"></asp:ListItem>
<asp:ListItem Text="False" Value="False"></asp:ListItem>
</asp:DropDownList>
<asp:label ID="mustApprove" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "MustApprove") %>'></asp:label>
</td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr class="listcolor">
<td style="border:0px; border-right:1px solid #808080 ; border-bottom:0px solid #808080;">
<asp:DropDownList runat="server" ID="ddlMustApprove" CssClass="hidden" OnTextChanged="selection_Change" EnableViewState="true" AutoPostBack="true" >
<asp:ListItem Text="True" Value="True"></asp:ListItem>
<asp:ListItem Text="False" Value="False"></asp:ListItem>
</asp:DropDownList>
<asp:label ID="mustApprove" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "MustApprove") %>'></asp:label>
</td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
My code is written in VS 2010 using .Net 4.0 and AjaxControlToolkit 4.1.60919.
Thanks
jason
ma.Text = currentChoice.MustApprove
replace this line with the following one.
if(ma.items.FindByText(currentChoice.MustApprove) != null)
{
ma.SelectedIndex = -1;
ma.items.FindByText(currentChoice.MustApprove).selected = true;
}
Just set the selectedindex of the dropdown as -1 like above.

checkbox.checked is not working in a listview

I've got an aspx using master pages and .net 4. I've using the same code on 4 different forms. I've copied and pasted it from the other forms that are working. Here is the code.
The listview is named lvMisc_Attachment, here is the Checkbox code
<asp:CheckBox ID="chkChecked" runat="server" Checked='<%#eval("Checked") %>' />
and here is the code behind that is happening when someone clicks a linkbutton, the linkbutton calls teh MiscAttachment_ItemsChecked function.
Private Function MiscAttachment_ItemsChecked() As String
Dim mString As String = String.Empty
For Each lv In Me.lvMisc_Attachment.Items
If CType(lv.FindControl("chkChecked"), CheckBox).Checked = True Then
If mString.Length = 0 Then
mString = CType(lv.FindControl("hfMisc_AttachmentID"), HiddenField).Value
Else
mString = mString & "," & CType(lv.FindControl("hfMisc_AttachmentID"), HiddenField).Value
End If
End If
Next
Return mString
End Function
The checkbox does not show up as being checked when it is. It is getting checked after the page renders.
Add AutoPostback="true" to your checkbox in order to post contol whan he changes
<asp:CheckBox ID="chkChecked" runat="server" Checked='<%#eval("Checked") %>' AutoPostback="true"/>
I found the problem. I forgot to do a if page.ispost=true on the page_Load.. the listview was getting repopulated so the checkbox wasn't checked due to the reload.

ASP.NET Find DropDown Value Inside Repeater Control Part II

ive had a few questions on this subject, still having problems.
I want to find the values from a number of dropdown and textbox controls inside a repeater control.
db.ConnectionString = SystemConnString
db.Open()
Dim selectedAdTitle As String = ""
Dim enteredAdFullName As String = ""
cmd.Parameters.Add(New SqlParameter("#TransactionID", TransactionID))
cmd.Parameters.Add(New SqlParameter("#AdTitle", selectedAdTitle))
cmd.Parameters.Add(New SqlParameter("#AdFullName", enteredAdFullName))
For i As Integer = 0 To myRepeater.Items.Count - 1
Dim AdTitle As DropDownList = DirectCast(myRepeater.Items(i).FindControl("AdTitle"), DropDownList)
Dim AdFullName As TextBox = DirectCast(myRepeater.Items(i).FindControl("AdFullName"), TextBox)
selectedAdTitle = AdTitle.Text
enteredAdFullName = AdFullName.Text
cmd.Parameters("#AdTitle").Value = selectedAdTitle
cmd.Parameters("#AdFullName").Value = enteredAdFullName
SQL = ""
SQL = SQL & "INSERT INTO InsuredPersons (TransactionID,Title,FullName) VALUES ("
SQL = SQL & "#TransactionID,"
SQL = SQL & "#AdTitle,"
SQL = SQL & "#AdFullName"
SQL = SQL & ")"
cmd.CommandText = SQL
cmd.Connection = db
cmd.ExecuteNonQuery()
Next
AdTitle and AdFullName dont seem to be bringing across the values. There is no error so they have found the control ok. Below is the ASPX file code.
<asp:Repeater ID="myRepeater" runat="server">
<ItemTemplate>
<asp:DropDownList ID="AdTitle" runat="server">
<asp:ListItem Selected="True" Value="" Text=""/>
<asp:ListItem Selected="False" Value="Miss" Text="Miss"/>
<asp:ListItem Selected="False" Value="Ms" Text="Ms"/>
<asp:ListItem Selected="False" Value="Mrs" Text="Mrs"/>
<asp:ListItem Selected="False" Value="Mr" Text="Mr"/>
<asp:ListItem Selected="False" Value="Other" Text="Other"/>
</asp:DropDownList>
<asp:TextBox ID="AdFullName" runat="server"></asp:TextBox>
</ItemTemplate>
Edit:
Repeater is constructed on page load
Dim repeatTimes((TotalAdInsured - 1)) As Integer
myRepeater.DataSource = repeatTimes
myRepeater.DataBind()
DirectCast is done on button click
Protected Sub continueButtonDetails_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles continueButtonDetails.Click
Answer: Had to put IsPostback around Repeater Construction.
If Not IsPostBack() Then
Dim repeatTimes((TotalAdInsured - 1)) As Integer
myRepeater.DataSource = repeatTimes
myRepeater.DataBind()
End If
First off I think you want:
myDropDown.SelectedItem.Text
Rather Than
myDropDown.Text
Also why do you have two ItemTemplates? I didn't know you could even do that...
Are you interacting with any of the TextBoxes or DropDowns at any other point during the page lifecycle?
Try putting a PostBack check around the repeater databinding. I think whats happening is your loading the controls dynamically, therefore they have no viewstate, therefore the values will always be empty.
Make sure your are running your code at the correct point in the page life cycle. If you are doing it too early (for example in the OnInit) then it won't have the values from the client yet. Try moving it to your OnCommand()/OnSubmit() event and see what happens. Here are some references on ASP.NET Page Life Cycle:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
http://www.15seconds.com/issue/020102.htm
http://www.beansoftware.com/ASP.NET-Tutorials/Page-Life-Cycle.aspx
Picture of asp.net page life cycle

Resources