Missing something nested in FindControl but always get Null - asp.net

Literally have read and tried all solutions in Stackoverflow to no avail.
I am trying to get the value of different Dropdownlists genereated from a Repeater and another one just generated on the go, plain and simple.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
I am trying to get all the selectedValue's of all the dropdownLists genereated thru Repeater and the one that is plain and simply there.
<asp:DropDownList ID="reasonFamily" runat="server">
<asp:ListItem Enabled="true" Text="--------" Value="-1"></asp:ListItem>
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
which looking in the front end, I am getting something like...
<select name="ctl00$ContentPlaceHolder1$reasonFamily" id="ContentPlaceHolder1_reasonFamily">
Which looks good, since I did a button and tried to get this value...
DropDownList ctr = Page.FindControl("Content2").FindControl("reasonFamily") as DropDownList;
TextBox.Text = ctr.SelectedValue;
I could just get the value of reasonFamily.SelectedValue and get finished with... But the problem is, there is another section with a repeater that creates several DropDownList and I need to find all of them and get all their values and Send them to the DB. The DropDownList is all nested in...
<asp:Repeater ID="repStudents" runat="server">
<asp:DropDownList ID="reasonStd" runat="server">
<asp:ListItem Enabled="true" Text="--------" Value="-1"></asp:ListItem>
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
I tried getting finding all of the dropdownlist, but all I get is NULL.
UPDATE: I was able to get the one that is not in the Repeater, but other still eludes me, even tho I have almost tried all the possible choices.
<select name="ctl00$ContentPlaceHolder1$reasonFamily" id="ContentPlaceHolder1_reasonFamily"> // This I was able to access with:
DropDownList ctr = this.Master.FindControl("ContentPlaceHolder1").FindControl("reasonFamily") as DropDownList;
<select name="ctl00$ContentPlaceHolder1$repStudents$ctl01$reasonStd" id="ContentPlaceHolder1_repStudents_reasonStd_1"> //This I could not. Tried all of this:
DropDownList ctr = this.Master.FindControl("ContentPlaceHolder1").FindControl("reasonStd_1") as DropDownList;
DropDownList ctr = this.Master.FindControl("ContentPlaceHolder1").FindControl("repStudents").FindControl("reasonStd_1") as DropDownList;
DropDownList ctr = this.Master.FindControl("ContentPlaceHolder1").FindControl("repStudents")FindControl("reasonStd").FinControl("1") as DropDownList;

Ok, so the 2nd or some other repeater issue - we leave that separate for now.
that last answer SHOWS how we can grab those values - it really the same code.
So, you have a repeater. It has maybe 1 or 15 rows. So, we want to get/grab the drop down list from each row of the repeater.
So, say we have this markup in the repeater (I included your above dropdown list).
So, we have this simple markup:
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<div style="border-style:solid;color:black;width:250px">
<div style="padding:5px;text-align:right">
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' Width="130px" />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' Width="130px" />
<br />
<asp:DropDownList ID="reasonFamily" runat="server">
<asp:ListItem Enabled="true" Text="--------" Value="-1"></asp:ListItem>
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
</asp:DropDownList>
<br />
</div>
</div>
</ItemTemplate>
Ok, now it don't matter if this has 2, or 30 rows. Lets assume it has 3 rows of data. so the above now shows this:
So say when we click on the above button, then we need code (the SAME code in the last question). so the code to process each row, get the values (including the dropdown) could be like this for that button click:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (RepeaterItem rRow in Repeater1.Items)
{
// get First Name.
Debug.Print(rRow.FindControl("txtFirst") as TextBox.Text);
// get LastName
Debug.Print(rRow.FindControl("txtLast") as TextBox.Text);
// get value of drop down box
string strDropDownChoice = rRow.FindControl("reasonFamily") as DropDownList.Text;
Debug.Print("Drop Down option picked = " + strDropDownChoice);
}
}
And output from above loop code would be this:
Output:
Albert
Kallal
Drop Down option picked = 1
Darcy
Caroll
Drop Down option picked = 2
Don
Grant
Drop Down option picked = 2
So, once again, I don't see any real issue or problem with looping over the rows in the data repeater, and then pulling out the values from text box, check box, or a drop down list - it is all quite much the same.

Related

Update on GridView combobox not updating

I am trying to bind the DropDownList(DDL) with my entity datasource. The GridView(GV) is bound to a different EntityDataSource than the DDL. The GV's EntityDataSource has a navigation property 'Bag' for the relationship. In edit mode I can pick a different item, but it does not update the database for that record. I did use the include for the navigations in the EntityDataSource. I am sure the wiring is not correct. I have tried searching with no luck so far. Thanks for the help.
<asp:TemplateField HeaderText="Bag">
<ItemTemplate >
<asp:Label ID="lbEditBag" Text='<%#Eval("Bag.Item1") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate >
<asp:DropDownList runat="server" ID="ddlBags" DataSourceID="edsBags" DataTextField="Amount" DataValueField="BagId" />
</EditItemTemplate>
</asp:TemplateField>
DonA, if you've not found your answer yet I will explain what I have done to do something similar to what your after I believe.
In a gridview I have various asp:TempleteField's, one which is like this:-
<ItemTemplate>
<asp:Label ID="lblActive" runat="server" Text='<%# Bind("Active") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<%--<asp:TextBox ID="txtboxActive" runat="server" Text='<%# Bind("Active") %>' Width="20px" TextMode="SingleLine" CssClass="textboxEdit"></asp:TextBox>--%>
<asp:DropDownList ID="activeDDL" CausesValidation="False" AutoPostBack="False" runat="server"> <asp:ListItem Text="No" Value="0"></asp:ListItem>
<asp:ListItem Text="Yes" Value="1" Selected="True"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
which as you can see has two dropdownlist items in the EditItemTemplete (I also left in similar code to yours that I used to use to bind to a database for the DDL values but I don't use anymore so is commented out)
then alongside the ID, runat="server", DataKeyNames, etc. in
<asp:Gridview ID=""...
i have
OnRowUpdated="info_GridView_RowUpdated"
This then runs in my C# code behind an SQL function to update the database table with the setting from the DDL, like so (I have also put in a few other Gridview.Databind() to reset my other gridviews)
protected void info_GridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
// The update operation was successful. Retrieve the row being edited.
int index = info_GridView.EditIndex;
GridViewRow row = info_GridView.Rows[index];
int itemID = Convert.ToInt32(row.Cells[4].Text); // Cells[4] is only one available as others are being edited!
// update Active value in the database //
comm = new SqlCommand("UPDATE Products SET Active=#active WHERE ItemID=#itemID", objConn);
comm.Parameters.AddWithValue("#active", ddlValue); // this stores DDL value in database
comm.Parameters.AddWithValue("#itemID", itemID);// Convert.ToInt32(propertyRefTextBox.Text));
objConn.Open();
comm.ExecuteNonQuery();
objConn.Close();
// force update and reset selectedIndex of other gridviews //
Category_GridView.DataBind();
editImages_GridView.DataBind();
Category_GridView.SelectedIndex = -1;
editImages_GridView.SelectedIndex = -1;
}
hope the above helps.
Trev.

ASP.NET Dropdrownlist croaks with SelectValue Assignment

This is my aspx
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ObjectDataSource ID="DSCategories" runat="server"
SelectMethod="GetCategories" TypeName="BAL.CategoryBAL">
</asp:ObjectDataSource>
<div id="Criteria">
<h3>Category:</h3>
<asp:DropDownList ID="ddlCategories" runat="server"
DataSourceID="DSCategories" DataTextField="Description"
DataValueField="Code">
</asp:DropDownList>
<asp:Button ID="btnSetCriteria" runat="server" Text="Set Criteria" />
</div>
</asp:Content>
And this is briefly my Page_Load code:
SearchCriteriaBAL scb = SearchCriteriaBAL.GetSearchCriteria(id);
string cat = String.Empty;
if (!string.IsNullOrEmpty(scb.Criteria))
{
cat = ParseCriteria(scb.Criteria);
ddlCategories.SelectedValue = cat;
}
I break on the SelectedValue assignment line and see the items in the dropdownlist and I see a valid value for cat and it is in the list but I get:
'ddlCategories' has a SelectedValue
which is invalid because it does not
exist in the list of items. Parameter
name: value
It seems to be doing the GetCategories AFTER I set the selectedValue and then it dies.
I placed it on its own test page for fear of interaction but it still fails. Has anyone seen this before?
You could try selecting the item this way:
ddlCategories.Items.FindByValue(cat).Selected = true;
Which of course wont' work if cat really isn't in the Items collection
Write the function on DropDownList's DataBound event instead of Page_Load
Occurs after the server control binds
to a data source.
<asp:DropDownList ID="ddlCategories" runat="server"
DataSourceID="DSCategories"
DataTextField="Description"
DataValueField="Code"
OnDataBound="ddlCategories_DataBound">
</asp:DropDownList>
Rather than using SelectedValue, I would have opted
ddlCategories.Items.FindByValue(cat.Trim()).Selected = true;

ASP.NET DropDownList - GetSelectedIndices missing one selected item

Maybe I'm losing my mind - I thought this was straight forward.
ListCode.DataTextField = "code_desc";
ListCode.DataValueField = "code_id";
ListCode.DataSource = Foo.GetCodes();
ListCode.DataBind();
The selection mode is set to multipls and all is good, about 50 items with appropriate values displays. Then I select 5 items and submit the form. I do a
int[] indices = ListCode.GetSelectedIndices();
and the array only has the first four items that I selected. It seems that if I select multiple items in the list and submit the form, I'm only able to retrieve all but the last selected item - it doesn't matter if I use GetSelectedIndices or if I iterate through each item in the list.
Any help would be greatly appreciated.
You must be using a ListBox I assume. I made the following test app:
<asp:ListBox ID="lstTest" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="Test1" Value="1" />
<asp:ListItem Text="Test2" Value="2" />
<asp:ListItem Text="Test3" Value="3" />
<asp:ListItem Text="Test4" Value="4" />
</asp:ListBox>
<asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click" />
<asp:Label ID="lblTest" runat="server" />
protected void btnTest_Click(object sender, System.EventArgs e)
{
int[] selectedIndexes = lstTest.GetSelectedIndices();
lblTest.Text = selectedIndexes.Length.ToString();
}
Seems to work fine so I have to assume it has something to do with your binding or when you are fetching the indicies. Can you post a trimmed down version of your broken code?
Not really an answer, but I swapped in a checkboxlist and it worked like a champ.

Handling a DropDownList in a Nested ListView

I have two nested .net ListViews. I need to filter the contents of the inner listview by selecting from a dropdown list in the outer listview. The layout of the control is like this:
<asp:listview id="lvOuter" runat="server" onitemdatabound="lvOuter_OnItemDataBound"
onitemcommand="lvOuter_OnItemCommand" onitemcreated="lvOuter_ItemCreated" onselectedindexchanged="lvOuter_SelectedIndexChanged">
<layouttemplate>
<ul>
<asp:placeholder id="itemPlaceholder" runat="server" />
</ul>
</layouttemplate>
<itemtemplate>
<asp:dropdownlist id="ddlTest" runat="server" onselectedindexchanged="ddlTerm_SelectedIndexChanged" autopostback="true" >
<asp:listitem text="6" value="6"/>
<asp:listitem text="9" value="9"/>
</asp:dropdownlist>
<asp:listview id="lvInner" runat="server" onselectedindexchanging="lvInner_SelectedIndexChanging"
onitemdatabound="lvInner_ItemDataBound" onitemcommand="lvInner_OnItemCommand">
<layouttemplate>
<asp:placeholder id="itemPlaceholder" runat="server" />
</layouttemplate>
<itemtemplate>
<!--Results displayed here-->
</itemtemplate>
</asp:listview>
</itemtemplate>
</asp:listview>
On the page load I bind data to the outer listview and on OnItemDataBound I bind the inner listview. This is all working fine, but what I need to do now is to re-bind the inner listview with a new query that includes the parameter from the drop down list. This should happen when the user selects a new value in the drop downlist. (OnSelectedIndexChanged) I can access the value easily enough through the sender, as so:
protected void ddlMyDropDown_OnSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlMyDropDown = sender as DropDownList;
string value = ddlMyDropDown.SelectedValue;
}
but I'm unable to then find the inner listview relating to that dropdown in order to bind the results of the new query with the added where clause. I'm sure this must be a pretty common requirement. Any pointers would be greatly appreciated.
Have you tried using something like <%# Eval("value", "{0}") %> as seen here
I seem to recall doing something akin to yours with this. It has been awhile since I have done this so sorry if this is not accurate.

How to set Custom Text into DropdownList in ASP.Net

I have dropdown list control in one of my application and when I add Items in it from database Its displaying the first Item into Dropdown list by default but I want to display someother text into this like "Select Item from the List" Is there any way I can do this .
Also Can you please help me setting the same value from javascript
On the ASP.NET side of things, you can create the DropDownList with AppendDataBoundItems="true" and any items you bind to it will come after the default:
<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
<asp:ListItem Text="Select something" Value="-1" />
</asp:DropDownList>
As for doing the same thing completely in Javascript, you can do it with a function like this:
function addFirstItem(list, text, value)
{
var newOption = document.createElement("option");
newOption.text = text;
newOption.value = value;
list.options.add(newOption);
}
addFirstItem(document.getElementById("yourListId"), "Select something", "-1");
Or with jQuery (there is probably something much cleaner, especially for creating a new option tag, but this works):
$("#yourListId option:first").before("<option value='-1'>Select something</option>");
Patridge answer is correct, however if you are using the asp method and still run into a problem, add the items tag to the listitem.
<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
<items>
<asp:ListItem Text="Select something" Value="-1">--Select Something--</asp:ListItem>
</items>
</asp:DropDownList>

Resources