Dropdownlist Datasource and adding extra item from C# - c#

I have a DropDownList that is associated with a DataSource in the aspx page. I need to add one more item when the page is loaded.
My Code:
<asp:LabelDropDownList ID="ddlVisualTemplate" runat="server" LabelText="Visual Template:" DataSourceID="VisualTemplateDataSource" DataTextField="Name" DataValueField="Id" AutoPostBack="true" OnSelectedIndexChanged="ddlVisualTemplate_SelectedIndexChanged"/>
<asp:EntityDataSource ID="VisualTemplateDataSource" runat="server"
ConnectionString="name=Entities"
DefaultContainerName="Entities" EnableFlattening="False"
EntitySetName="tbEmailVisualTemplates">
And I am trying to an extra item to it:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlVisualTemplate.Items.Add(new ListItem("None", string.Empty));
}
}
If I debug the code, it goes through it. But When the page is displayed dropdown doesn't contain "None".

Probably too late for the original poster, but maybe useful for other users:
You can add the value "None", "Choose value", etc. in the designer (or in the code) and prevent DataBind from overwriting it, by setting AppendDataBoundItems="true". This will make DataBind append rather than clear.
Below example from Scott Guthrie's post ListControl.AppendDataBoundItems Property in ASP.NET 2.0.
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource1" DataTextField="state" DataValueField="state">
<asp:ListItem Text="(Select a State)" Value="" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
SelectCommand="SELECT DISTINCT [state] FROM [authors]">
</asp:SqlDataSource>

It's most probably because you're adding the item before the DataBind(). If you want to add an item with
ddlVisualTemplate.Items.Add()
then you have to do it after the dropdown is being bound.
If you look at http://msdn.microsoft.com/en-us/library/ms178472.aspx then DataBind is being done in PreRenderComplete. So you have to add the element in some event that occurs after PreRenderComplete.
Or you could do it on the ddlVisualTemplate.DataBound event.

You could easily fix this by setting the datasource prgrammatically:
ddlVisualTemplate.DataSource = VisualTemplateDataSource;
ddlVisualTemplate.DataBind();
ddlVisualTemplate.Items.Add(new ListItem("None", string.Empty));
BTW, these datasource controls are a wrong thing in asp.net in my opinion. I don't like the idea of defining the data source and giving the control over db connections to the aspx page. For a better way of doing this just google about session per request pattern, separation of concerns and n-tier apps.
Update: instead of "VisualTemplateDataSource" you could call directly the data. I don't know EF, but it might be like this: "DataContext.tbEmailVisualTemplates". You have to set your datacontext. And then you can get rid of the datasource control.

Use this to add an item in the bound dropdown list at 0 index
ddlTicketType.Items.Insert(0, new ListItem("All", "0"));

This fixed it for me but it puts the value in the end.
protected void ddlTest_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlTest.Items.Add(new ListItem("All", string.Empty));
}
}

Related

Selected Index doesn't change

I have an ASP.NET DropDownList control, with a onSelectedIndexChanged event. I also have the AutoPostBack="true" that many have said would fix the problem. However I don't think that is where the problem lays... My Html code and C# code are below for reference. The thing is the code works, but only when I press the enter key while editing the drop down box. If I simply click on an object in the drop down then the event will not fire. If I change the selected item so the "selected" text in the drop down says "ASP" and I then inspect the element using the browser I see that the Selected="True" part of the ListItem is still on the first item... It doesn't change in there. It changes with an enter key but not with a mouse click. Any help is welcome and much appreciated.
HTML:
<div class="ui-widget">
<asp:DropDownList id="Select1" OnSelectedIndexChanged="Select1_SomethingChange" runat="server" AutoPostBack="true">
<asp:ListItem Selected="True" Value="White"> White </asp:ListItem>
<asp:ListItem Value="Select one...">Select one...</asp:ListItem>
<asp:ListItem Value="ActionScript">ActionScript</asp:ListItem>
<asp:ListItem Value="AppleScript">AppleScript</asp:ListItem>
<asp:ListItem Value="Asp">Asp</asp:ListItem>
<asp:ListItem Value="BASIC">BASIC</asp:ListItem>
</asp:DropDownList>
</div>
C#:
protected void Select1_SomethingChange(object sender, EventArgs e)
{
//something is meant to happen here
}
It may be caused by data binding your dropdownlist in Page_Load method.
Please, surround it (data binding) with
if(!IsPostBack){
// data binding.
}
Hope, it help!
AutoPostBack="true"
maybe you miss this option...
Your code works fine, there could be something in code which changes the implementation. I have debug your code and it's showing the selected item in output window. Please verify if there is some javascript code which is causing issue to call dropdown selectedIndexChanged event.
protected void Select1_SomethingChange(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
Debug.WriteLine(ddl.SelectedItem.Text);
}

How to execute a query when dropdownlist selected index changes

I have a DropDownList which is populated using a sqldatasource, i.e., from database and their is a grid view which is populated with another sqldatasource connected to using the value of dropdownlist.
But it does not execute the query dynamically. I want that whenever the value of dropdownlist changes, the grid view should update.
Code please..
ASPX code
<asp:DropDownList id="ddlCountry" AutoPostBack="True" runat="server" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" ></asp:DropDownList>
And CS code
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
FillYourGridviewHere();
}
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource2" DataTextField="ssn" DataValueField="ssn"
AutoPostBack=true>
</asp:DropDownList>
This Worked. Thank You.!!
You can just write the dynamic code for populating the grid into a function and bind that function to the dropdownlist onChange event.
Say "mydropdown" is the id of your dropdownlist and "dochanges" is a function that executes your dynamic codes. So you just need to bind the dochanges function to the change event of your dropdownlist.
$('#mydropown').bind('change',function(){
dochanges(); //call the dynamic function where you update your grid
});

Create a Repeater control in ASP.Net

I'm using two drop down and bind values to that drop down.
Now am adding a new button add_new.
I want to create the above drop downs below when I click the add button and maintain the previous selected values. Please help me to do this.
You can achieve the desired result using Repeater control of ASP.Net. You can create any type of template as you wish, see the code below:
ASPX:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" />
<asp:DropDownList ID="DropDownList2" runat="server" />
<br />
</ItemTemplate>
</asp:Repeater>
CodeBehind:
protected void Button1_Click(object sender, EventArgs e)
{
// data fetching logic
Repeater1.DataSource = data;
Repeater1.DataBind();
}
Hard to answer without a better explanation and code samples but from experience doing anything with dropdowns over postbacks is better controlled with hidden fields. Set the value of the hidden field with javascript. Please provide more detail.

DetailsView FindControl() returns null after some postbacks

I've been working for a long time with GridViews and DetailsViews, but yesterday I've come across a new scenario, which I quite do not understand.
I have a GridView with ImageButton (CommandName="Insert") which will change the mode of the DetailsView to Insert. Afterwards I'll look for a DropDownList inside that DetailsView and add some items dynamically. Works fine, but one first the first time I press that ImageButton. If I click on "Cancel" in the DetailsView and press the ImageButton again, the .FindControl() Method returns null. What life cycle problem am I facing here?
I've created this sample: (To make it run in your Visual Studio, just bind a DataSource to the DetailsView, otherwise it will not be rendered)
Markup:
<asp:GridView ID="gvCategory" runat="server" OnRowCommand="gvCategory_RowCommand">
<Columns>
</Columns>
<EmptyDataTemplate>
<asp:ImageButton ImageUrl="~/images/add.png" ID="ibAdd" runat="server" CommandName="Insert" />
</EmptyDataTemplate>
</asp:GridView>
<asp:DetailsView ID="dvCategory" runat="server" Width="150px" AutoGenerateRows="false"
AutoGenerateInsertButton="True" DataSourceID="LinqDataSource1">
<Fields>
<asp:TemplateField HeaderText="foo">
<InsertItemTemplate>
<asp:DropDownList ID="ddlCategory" runat="server" Width="150"></asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView><asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="WebApplication1.DataClasses1DataContext"
TableName="Categories"></asp:LinqDataSource>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.gvCategory.DataBind();
}
}
protected void gvCategory_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
this.dvCategory.ChangeMode(DetailsViewMode.Insert);
DropDownList _ddlCat = (DropDownList)this.dvCategory.FindControl("ddlCategory");
if (_ddlCat != null)
{
_ddlCat.Items.Clear();
_ddlCat.Items.Add(new ListItem() { Text = "-- empty --", Value = "-1" });
}
}
}
I have also tried using a ItemTemplate, and not a InsertItemTemplate, but this results in the same. After using the ChangeMode-Method the DetailsView.CurrentMode == InsertMode. The only thing I can think of is, that the markup is already generated for the ItemTemplate and changing the Mode to InsertMode can't affect the rendered markup, or something like this.
Does anybody have a solution to this? =)
I think you are on the right track. It's hard to tell without seeing all of the code, but basically any time you change the rendering mode of a row in a repeater-type control you need to rebind it so that it's re-rendered. The fact that FindControl is returning NULL means only one thing: THE CONTROL IS NOT THERE. Which means it was not rendered. You can verify this by looking at the control hierarchy.
So, in your handler for Cancel are you rebinding?

Adding Item to DataBound Drop Down List

Yes, I have read most of the topics here, but I can't find an answer that works.
I have Three drop-down lists. The first is databound to grab distinct experiment names. The user selects, page posts back, and the second drop-down menu displays distinct time points. This is where I need help. I need to add an item to THAT drop-down list whose ID, DataTextField, DataValueField are all TimePt.
Seems simple, but I can't get it to work.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
TimePt.DataSource = TimePTDD;
TimePt.DataValueField = "TimePt";
TimePt.DataTextField = "TimePt";
TimePt.DataBind();
TimePt.Items.Insert(0, new ListItem("--Select---", "0"));
TimePt.SelectedIndex = 0;
}
}
I'm missing sometthing.
Set AppendDataBoundItems="true" on your dropdown list and it should work.
Here's a similar question: How to add Item to SqlDataSource databound list
And another one about potential duplicates using this method and a workaround for it: Dropdownlist AppendDataboundItems (first item to be blank)
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
TimePt.DataValueField = "TimePt";
TimePt.DataTextField = "TimePt";
var times = TimePTDD.ToList();
times.Insert(0, new {TimePt="0",TimePt="--Select--"});
TimePt.DataSource = times;
TimePt.DataBind();
//TimePt.SelectedIndex = 0;
}
}
<asp:DropDownList ID="ExpAnalysisName" runat="server"
DataSourceID="DropDownEXP" DataTextField="ExpAnalysisName"
DataValueField="ExpAnalysisName" AppendDataBoundItems="true" AutoPostBack=true>
<asp:ListItem Selected="True" Value="0">Select an Experiment</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="DropDownEXP" runat="server"
ConnectionString="<%$ ConnectionStrings:SGMD3_DataBase %>" SelectCommand="SELECT DISTINCT ExpAnalysisName FROM VW_Data">
</asp:SqlDataSource>
<asp:DropDownList ID="TimePt" runat="server" AutoPostBack="True" DataSourceID="TimePTDD" DataTextField="TimePt"
DataValueField="TimePt">
</asp:DropDownList>
<asp:SqlDataSource ID="TimePTDD" runat="server"
ConnectionString="<%$ ConnectionStrings:SGMD3_DataBase %>" SelectCommand="SELECT DISTINCT TimePt
FROM VW_Data
WHERE ExpAnalysisName = #ExpAnalysisName">
<SelectParameters>
<asp:FormParameter FormField="ExpAnalysisName" Name="ExpAnalysisName" />
</SelectParameters>
</asp:SqlDataSource>
So you can have a reference.
I see that you're specifying the DataSource in two different ways - The DataSourceID in your markup as well as manually setting the DataSource in your codebehind. Try removing the DataSourceID from your markup and see if that helps.
It's been a little while since I've used ASP.NET too much, but I have a feeling your DropDownList is rebinding after the Page_Load which would replace your previous binding.
My bet is this is a page lifecycle issue. Per MSDN, each data bound control whose DataSourceID property is set calls its DataBind method.
I think the values are getting bound to the dropdown twice. First, when you manually bind and append the extra item in Page_Load and then the datasource is being bound inside the Page_PreRender event. Try bringing your Page_Load code into Page_PreRender. Hopefully the order helps.
I suggest using OnDataBound event of DropDownList control, and put your code behind there.
That you way you can combine DataSourceID with code behind.

Categories