ASP.NET Find DropDown Value Inside Repeater Control Part II - asp.net

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

Related

SelectedIndexChange Not Firing

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?

Change textbox value when selecting dropdownlist value

I have a dropdownlist control that shows the primary key from a table called model, and a textbox that should show another value(a foreign key) from that same table when I use the dropdownlist.
Both PK and FK have a single value.
Since I didn't have a clue how to do this, I used a search method that should be called everytime someone selects a new value from the dropdownlist.
Search code:
Public Function searchArea(ByVal model As String) As String
Dim mycon As New Connection
Using connection As New SqlConnection(mycon.GetConnectionString())
Using command As New SqlCommand()
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "SELECT area FROM model WHERE model= #model"
command.Parameters.AddWithValue("#model", model)
connection.Open()
Dim dataReader As SqlDataReader = command.ExecuteReader()
If (dataReader.Read()) Then
Return dataReader.ToString(0)'this query should always have a single value
End If
Return "Nothing"
End Using
End Using
End Function
Event code:
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim objModel As New ModelDAO 'the class where the method is
TextBox9.Text = objModel.searchArea(DropDownList1.Text)
End Sub
.
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
DataSourceID="SqlDataSource1" DataTextField="MODEL" DataValueField="MODEL">
<asp:ListItem Text="-Select-" Value="" />
</asp:DropDownList>
<asp:TextBox ID="TextBox9" runat="server" Enabled="False" Height="24px"
Width="219px"></asp:TextBox>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBUserInterfaceConnectionString %>"
SelectCommand="SELECT [MODEL] FROM [MODEL]">
</asp:SqlDataSource>
But as I thought, it doesn't work, can you help me please?
EDIT: Thanks, now it triggers, but I'm getting the value: 'S' that value doesn't belong to my table.Can you tell me if my search method is ok?
Try to add this
<asp:DropDownList ID="DropDownList1"
runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
.....
</asp:DropDownList>
Try to Load datareader into datatable and than use it to print data into the textbox..
Thank you everyone, I solved it with this:
Return dataReader.GetString(0)
instead of:
Return dataReader.ToString(0)
It was just a type conversion problem.

How to clear exisiting dropdownlist items when its content changes?

ddl2 populates based on ddl1 selected value successfully.
My issue is the data that is already present in ddl2 does not clear before appending the new data so ddl2 content just continues to grow every time ddl1 is changed.
<asp:DropDownList ID="ddl1" RunAt="Server" DataSourceID="sql1" DataValueField="ID1" DataTextField="Name2" AppendDataBoundItems="True" AutoPostBack="True">
<asp:ListItem Text="ALL" Selected="True" Value="0"/>
</asp:DropDownList>
<asp:DropDownList ID="ddl2" RunAt="Server" DataSourceID="sql2" DataValueField="ID2" DataTextField="Name2" AppendDataBoundItems="True" AutoPostBack="True">
<asp:ListItem Text="ALL" Selected="True" Value="0"/>
</asp:DropDownList>
<asp:SqlDataSource ID="sql1" RunAt="Server" SelectCommand="sp1" SelectCommandType="StoredProcedure"/>
<asp:SqlDataSource ID="sql2" RunAt="Server" SelectCommand="sp2" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Type="Int32" Name="ID1" ControlID="ddl1" PropertyName="SelectedValue"/>
</SelectParameters>
</asp:SqlDataSource>
I have tried re-databinding in code behind on selected index change and also items.clear with little success.
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
ddl2.Items.Clear()
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
QUESTION
How to get items present in an asp:dropdownlist to clear before new values are populated when the dropdownlists content is dependent on another dropdownlists selected value?
Please post any code in VB
Using ddl.Items.Clear() will clear the dropdownlist however you must be sure that your dropdownlist is not set to:
AppendDataBoundItems="True"
This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.
SOLUTION
Add AppendDataBoundItems="False" to your dropdownlist.
Now when data is rebound it will automatically clear all existing data beforehand.
Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.
TOP TIP
Still want a default list item adding to your dropdown but need to rebind data?
Use AppendDataBoundItems="False" to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.
ddl.Items.Insert(0, New ListItem("Select ...", ""))
You should clear out your listbbox prior to binding:
Me.ddl2.Items.Clear()
' now set datasource and bind
Please use the following
ddlCity.Items.Clear();
Just 2 simple steps to solve your issue
First of all check AppendDataBoundItems property and make it assign false
Secondly clear all the items using property .clear()
{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}
just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal
e As EventArgs)
//ddl2.Items.Clear()
ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub
and it worked just fine

How can I assign the value of textbox as part of dropdown value?

I have GridView DropDownList:
<asp:TemplateField HeaderText="Employer">
<ItemTemplate>
<asp:DropDownList ID="txtEmployer" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="SelectedIndexChanged">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem Value="AllScripts">AllScripts</asp:ListItem>
<asp:ListItem Value="Contractor">Contractor</asp:ListItem>
<asp:ListItem Value="Other">Other</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
ControlToValidate="txtEmployer" ErrorMessage="*"
InitialValue="Select"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
And a TextBox:
<asp:TemplateField HeaderText="Other">
<ItemTemplate>
<asp:TextBox ID="txtOther" runat="server" TabIndex="435"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ControlToValidate="txtOther" ErrorMessage="*"
SetFocusOnError="True"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
The TexBox, by default, is hidden on PageLoad.
When a user selects the "Other" option, the TextBox becomes visible allowing the user to enter whatever value he/she wants. This works good so far.
We can successfully collect the value of the DropDownList and insert into the database successfully.
However, we are trying to figure out how to insert the value of txtOther TextBox and insert as part of the DropDownList. Hopefully, this last sentence makes sense.
I have tried the folling:
Dim table As DataTable = TryCast(ViewState("CurrentTable"), DataTable)
If table IsNot Nothing Then
For Each row As DataRow In table.Rows
Dim txLName As String = TryCast(row.ItemArray(1), String)
Dim txName As String = TryCast(row.ItemArray(2), String)
Dim txEmail As String = TryCast(row.ItemArray(3), String)
Dim txRole As String = TryCast(row.ItemArray(4), String)
Dim txPhone As String = TryCast(row.ItemArray(5), String)
Dim drpEmpl As String = TryCast(row.ItemArray(6), String)
If drpEmpl = "Other" Then
drpEmpl = txtOther.Text
Else
drpEmpl = TryCast(row.ItemArray(6), String)
End If
I am getting an error that txtOther.Text is not declared and may be inaccessible.
drpEmpl is the name of the DropDownList.
I have tried:
drpEmpl = gridview1.FindControl("txtOther")
But same issue.
Here is something I would try.
User enters text into txtOther and submits page
Take what user submitter and store it into viewstate variable (some array may be best for this in case more values are needed)
Modify your txtEmployer and add event handler for OnLoad
In the event handler for OnLoad you just add another option for drop down list.
foreach (string s in ArrayOfPreviouslyAddedValues){
ddl.Items.Add(new ListItem(s, s));
}
Another option is to store all values for all options in some background source (database or what ever) and to programatically databind values to your drop down list.
This is C# but you see the point.

Checkboxes in usercontrol won't check although they say they are

I have a simple usercontrol, with a datalist, and checkboxes inside.
<asp:DataList ID="DataListDroits" runat="server" DataKeyField="droit_id" DataSourceID="SqlDroits">
<ItemTemplate>
<asp:HiddenField ID="HiddenFieldDroitID" runat="server" Value='<%# Eval("droit_id") %>' />
<asp:CheckBox ID="CheckBoxDroit" runat="server" Text='<%# Eval("droit_label") %>' />
</ItemTemplate>
</asp:DataList>
I check them using code behind in the usercontrol :
Public Sub CheckRole(ByVal role As Integer)
For Each dliOrganisme As DataListItem In Me.DataListOrganismes.Items
Dim DataListDroits As DataList = dliOrganisme.FindControl("DataListDroits")
If DataListDroits IsNot Nothing Then
For Each dliDroit As DataListItem In DataListDroits.Items
If role = CInt(CType(dliDroit.FindControl("HiddenFieldDroitID"), HiddenField).Value) Then
Dim CheckBoxDroit As CheckBox = dliDroit.FindControl("CheckBoxDroit")
CheckBoxDroit.Checked = True
End If
Next ' DataListDroits
End If
Next ' DataListItem
End Sub
And in the page_load of the calling webform :
Dim CheckBoxesRoles1 As ASP.organisme_checkboxesroles_ascx = Me.FormViewRubrique.FindControl("CheckBoxesRoles1")
Dim rolesCoches As New List(Of Integer)
Dim cmdRoles As New SqlCommand("SELECT droit_id FROM o_droit_rubrique WHERE rubrique_id = #rubrique", conn)
cmdRoles.Parameters.AddWithValue("rubrique", Request.QueryString("rid"))
Dim rdrRoles As SqlDataReader = cmdRoles.ExecuteReader
While rdrRoles.Read
CheckBoxesRoles1.CheckRole(rdrRoles("droit_id"))
End While
rdrRoles.Close()
... and yet, they are not checked.
But if I do this :
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
Dim CheckBoxesRoles1 As ASP.organisme_checkboxesroles_ascx = Me.FormViewRubrique.FindControl("CheckBoxesRoles1")
If CheckBoxesRoles1 IsNot Nothing Then
For Each role As Integer In CheckBoxesRoles1.CheckedRoles
Response.Write("role : " & role & "<br>")
Next
End If
End Sub
I tells me they are...
I'm going mad here ! Why does it tells me they are checked while they obviously are not ?
Well... for one thing, you aren't checking if your checkboxes are checked, all you're doing is outputting the value of "role". What exactly are you expecting here?
Two suggestions:
1) Set the Checked property of your CheckBox in the aspx like so:
<asp:CheckBox ID="CheckBoxDroit" runat="server" Text='<%# Eval("droit_label") %>' Checked='<%# (Eval("droit_id") > 0).ToString()' />
2) Set the property in OnItemDataBound in code-behind
One of two things is happening: Either the code you expect to be executing is not really executing (ie, is your if block ever true? Is the control not being found? Try a breakpoint), OR you are doing it at the wrong time -- after the page has already been rendered.

Resources