Dynamic dropdownlist in repeater, ASP.NET - asp.net

Basically, the codes I have is from here : http://ranafaisal.wordpress.com/2009/02/17/dynamically-adding-removing-textboxes-in-aspnet-repeater/
However, the thing is that, I will need a dropdownlist with textboxes. The purpose of having dropdownlist is to allow users to select their country of origin. They have the option to Add or Remove the particulars they have entered before.
This is my error message:
'ddlName' has a SelectedValue which is
invalid because it does not exist in
the list of items. Parameter name:
value
This is my dropdownlist code inside a repeater in Default.aspx
<asp:DropDownList ID="ddlName" runat="server" SelectedValue='<%# DataBinder.Eval(Container.DataItem, "ddl") %>'></asp:DropDownList>
The codes behind is exactly the same as the link I provided.
Points to note: There is no database involved.
Please not tell me to google or anything because I have been googling for the past few hours, to no avail. I definitely have googled enough, and tried the solutions given by others before posting here. I am pretty much at my wits end
To add-on, I cannot even start-up my application because of the dropdownlist problem.

The problem is you need to fill the DropDownList possible options before you set the selected value which you are trying to do inline with the Eval. I would switch it to use the OnDataBinding of the DropDownList and do what you need there.
Example:
<asp:DropDownList ID="ddlName" runat="server" OnDataBinding="ddlName_DataBinding" />
protected void ddlName_DataBinding(object sender, System.EventArgs e)
{
DropDownList ddl = (DropDownList)(sender);
// Fill your ddl here (eg. ddl.Items.Add("abc", xyz");
// Make sure the value you are going to set the selected item to has been added
// Now set the selected value since it will now exist.
ddl.SelectedValue = Eval("ddl").ToString();
}

Related

asp:checkedchanged event not firing?

there. I have a gridview with a column of check boxes which was working when it was a small test project but when adding it to a page on my teams project it stopped firing the checkedChanged event. The check mark still appears or disappears but nothing fires. The only major difference is I was using an sqlDataSource object at first but for the new project i had to bind it to a database in the behind code.
Here's my html:
<asp:TemplateField HeaderText="Create Incident">
<ItemTemplate>
<asp:CheckBox ID="Selections" runat="server" ViewStateMode = "Enabled" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
and some simple behindcode:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
Console.WriteLine("clicked!");
}
set AutoPostBack to True to enable post back
<asp:CheckBox ID="Selections" runat="server" ViewStateMode = "Enabled" OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="True" />
I found the solution. I added the conditional the block if(!page.isPostBack) around the stuff in my page load event.
Kept searching for about an hour till I found out that the actual reason why the OnCheckedChanged event was not firing on my page was due to duplication of names. Duh
An input control had a name 'submit' and there also exists a method in my JavaScript that is called submit(). The JavaScript interpreter was confused between the name of the control and a function, every time it needed to fire the event. Changed the name of the control and everything went back to working perfectly.

EntityDataSource Executes the Query twice

I have a page that binds data from an EntityDataSource to a paged ASP.NET ListView. The query is actually a fairly complex query and I don't know that an EDS is really the way to go but it's inherited code and I am hoping to resolve this issue without having to re-engineer the page completely.
The problem is that when the page is Posted Back, with a filter parameter, the query executes once without the filter and then once again with the filter. The problem is that the unfiltered resultset is 17+ million records and times the request out.
So my question is ...
Why is the query executing twice? I thought that it might have had something to do with the DataPager on the ListView but when I removed it from the page it didn't change anything.
Update: 2013/04/16
Thank you #bUKaneer and #lthibodeaux. I thought it would behelpful to add the request information to the OP.
As suggested, I commented out Pager control(s) and list view. Upon their removal all requests to the database stopped. I added back just the ListView and the query was executing twice again.
There are no additional event handlers assigned to the EDS itself.
<asp:EntityDataSource ID="edsSerialNumbers" runat="server" ContextTypeName="DBName.Entities" EnableFlattening="False"
EntitySetName="DIST_TABLE" Include="PRODUCT, DISTRIBUTION, DISTRIBUTION.COMPANY_SITE"
EnableUpdate ="true" EnableViewState="true"
OrderBy="it.DISTRIBUTION.DIST_NAME, it.PRODUCT.SERIAL_NUMBER"></asp:EntityDataSource>
The DataPager is actually embedded in a separate UserControl that is included outside of the ListView, and is included twice ...
<div class="dataTablePager">
<kqp:TablePager ID="pgrTop" runat="server" PagedControlID="lvSerialNumbers"/>
</div>
<asp:ListView ID="lvSerialNumbers" runat="server" DataKeyNames="ID" OnDataBound="lvSerialNumbers_DataBound" OnItemEditing ="lvSerialNumbers_ItemEditing" onitemdatabound="lvSerialNumbers_ItemDataBound" EnableViewState="true">
...
</asp:ListView>
<div class="dataTablePager">
<kqp:TablePager ID="pgrBot" runat="server" PagedControlID="lvSerialNumbers"/>
</div>
The only place in the code behind that the EDS is touched is here in the PreRender phase...
protected void Page_PreRender(object sender, EventArgs e)
{
if (!kqpFilters.IsFiltered && !IsPostBack)
{
lvSerialNumbers.DataSourceID = null;
}
else
{
lvSerialNumbers.DataSourceID = "edsSerialNumbers";
}
}
After commenting EVERYTHING out except the spot where the ListView's datasource is assigned to the EDS I was unable to resolve this problem.
I will work around it by ripping out the EDS and replacing it it with a call to a stored procedure instead. Very frustrating though as this problem exists on about 10-15 screens and without an alternative I will have to re-write each, from the ground up.

ASP.NET DropDownList not getting correct SelectedItem

We are using ASP.NET for one of our projects. However, when we are trying to read the SelectedItem or SelectedValue property of the DropDownList we are using in the callback function of a Link click, we are not getting the correct SelectedItem.
<FooterTemplate>
<asp:DropDownList ID="cmbTesters" ClientIDMode="Static" runat="server" Width="300px" DataSource='<%# PopulateTesterNames() %>' DataTextField="FullName" DataValueField = "PK_ID"></asp:DropDownList>
</FooterTemplate>
This is the DropDownList in the aspx file. The drop down is present within a GridView's Footer Row. We are invoking the following set of code on clicking a link.
if (int.TryParse(((DropDownList)dgCreateCPRVerificationResponse.FooterRow.FindControl("cmbTesters")).SelectedValue, out TesterID))
{
TesterID = int.Parse(((DropDownList)dgCreateCPRVerificationResponse.FooterRow.FindControl("cmbTesters")).SelectedValue);
}
The problem we are facing is that whatever value we choose, the SelectedValue is always of the first item in the list. We are using REST based URL defined in the global.asax file. Also note that this is not built on any framework.
Please help as soon as possible
Make sure to put the binding methods of the dropdownlist and the gridview inside if (!IsPostBack)

Child UserControl missing datasource when binding through ListView

I have a UserControl that takes a class object as property "DataSource." On DataBind, I apply properties of that object to controls -- TextBox, RadioButton, etc -- inside the UserControl.
This works great when I just set the UC on a page, bind, and go.
Now, I'm attempting to use this control in the ItemTemplate of a ListView like so;
<ItemTemplate><uc1:MyItem ID="MyItem1" runat="server" DataSource='<%# Container.DataItem %>' /></ItemTemplate>
and bind to an array of those objects. The array is populated but I'm reaching my DataBind method of the UC with DataSource = null. Am I missing something?
EDIT: Holidays kept me away from this.
So, apparently I was calling base.DataBind() too late. My LoadForm(DataSource) method to load the object into the form fields preceded base.DataBind(). Swapping them fixed allowed me access to DataSource with no problem.
public override void DataBind()
{
base.DataBind();
LoadForm(DataSource);
}
Am I understanding my problem right? Was I just doing things out of order?
The "<%# %>" syntax tells the compiler to run the associated code during the control's DataBinding event -- but DataSource needs to be set before the DataBinding event to be effective.
One way to work around the issue might be to do your binding-related processing after the DataBind event runs, such as in PreRender.
You just have to know that you might be reloading the page, and you may try to use the
if(!IsPostBack)
in your Page_Load(object sender, EventArgs e)

How do I add an empty first entry do an <asp:DropDownList>?

I have a dropdown, I have a datasource, I have AutoPostBack set to true.
I want to add a first entry to the datasource that says something like "--- select country ---" and selecting this entry won't cause postback.
This feels like it should be easy to do, yet I can't seem to be able to find a good solution.
Thanks.
In your aspx page (the important part is handling the DataBound event and setting CausesValidation="true" to force validation of a drop down list):
<asp:DropDownList ID="ddlCountries" runat="server" DataSourceID="dsCountries" AutoPostBack="true" OnDataBound="ddlCountries_DataBound" CausesValidation="true" />
<asp:RequiredFieldValidator ID="rfvCountries" runat="server" ControlToValidate="ddlCountries" Display="Dynamic" ErrorMessage="Please select a country." />
In your codebehind (it is important that the value of the inserted item is String.Empty for the required field validator to work!):
protected void ddlCountries_DataBound(Object sender, EventArgs e)
{
ddlCountries.Items.Insert(0, new ListItem("--- select country ---", String.Empty));
}
Note: If you don't want the validator's message to display, set the "Display" property to "None".
You can also add the row manually through the designer but you have to make sure that the DropDownList's property AppendDataBoundItems = True as well so that the databound rows are tacked onto the first row.
Previous answers deal with inserting the value, but I understand your problem is the AutoPostBack property. I suppose you dont want to postback that value and that's your problem, am I right?
Maybe there's a better solution, but I'd suggest not using AutoPostBack. You could handle postback automatically using the selected value change event.
IMHO if the AutoPostBack does not work as you want, it's always better to implement your own solution that to put some kind of "patch" over it to "fix" it.
Hope that helps
Use the insert method as others have suggested to add the item at index 0 with a value to indicate not selected ( for example 'unknown'). Then use validators, add a required field validator and set the InitialValue property to the value of the new list item ('unknown' in our example).
Set index 0 to be the selected item on page load and if not postback.
If the user doesn't select another option the validator will prevent the postback.
Hope that's what you are looking for.

Resources